php mysqli last insert id

3 Answers

after I get the last row from table2 I would like to insert it to table1. That is all I need

Go on:

  1. insert into table 1 with simple regular insert query
  2. get last insert id
  3. insert into table 2 with simple regular insert query

As simple as that

mysqli_insert_id returns 0 after insert

I would like to associate the image with firstname, can I retrieve the last rowand use it to insert to the other table? I tried $image = $mysqli->insert_id; then binding but it doesn't work. Can someone help me out?

 $image = $mysqli->insert_id;//this should come from table2
 $stmt = $mysqli->prepare("
  insert into table1 (username, firstname, lastname, image) 
  select ?,?,?,image from table2 t2 where username = ? and = ? 
 $stmt->bind_param('sssss', $username, $fname, $lname, $username, $image);

Get id of last inserted prepared statement

You can get last_insert_id only after query execution.

Try this example:

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());

$query = "INSERT INTO tableposts(id, name, location) VALUES (DEFAULT, '$name', '$location')";

printf ("New Record has id %d.\n", $mysqli->insert_id);

/* close connection */