Search code examples
phpmysqlsqllast-insert-id

How can I retrieve a last_insert_id from a specific query in a transaction?


I have a mysql transaction with three queries

In the third query I am trying to pull last_insert_id values from the two previous queries.

VALUES ('".$result1[last_id]."','".$result2[last_id]."')";

But it doesn't work. Any suggestions?


Solution

  • You should get the last insert ID first, and then inject it into the query. Assuming you're using the mysql_ functions:

    mysql_query($query1);
    $id1 = mysql_insert_id();
    
    mysql_query($query2);
    $id2 = mysql_insert_id();
    
    $query3 = "INSERT INTO ... VALUES (".$id1.", ".$id2.");";
    mysql_query($query3);