1

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?

Daniel Li
  • 14,976
  • 6
  • 43
  • 60
Richard
  • 209
  • 2
  • 10
  • When used in transactions, last_insert_id must be called before committing – Federkun Jul 18 '12 at 17:41
  • Array keys should be quoted. Unless they're in double quote string context. The quote and concatenation context switching in your example is redundant. – mario Jul 18 '12 at 17:42
  • @laxus: no, you can insert in the transaction, and still pull the id - you HAVE to be able to do that. But you can't do multiple inserts and then pull up the id of the n-2 or earlier inserts. – Marc B Jul 18 '12 at 17:44

3 Answers3

3

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);
Waleed Khan
  • 11,426
  • 6
  • 39
  • 70
1

Assuming that you are using MySQL database. You can get id like:

mysql_query($first_query);
$first_result_id = mysql_insert_id();

mysql_query($second_query);
$second_result_id = mysql_insert_id();

$third_query = "INSERT INTO table  (column1, column2) VALUES (".$first_result_id .", ".$second_result_id .");";
mysql_query($third_query);

Hope this helps

Sabari
  • 6,205
  • 1
  • 27
  • 36
1

You can use MySQL to

SELECT LAST_INSERT_ID()

which will retrieve the last insert ID in the given transaction. You can also do this in other DBMS, but you are obviously using MySQL.

Since you are, the MySQL APIs in php have shortcuts for this too:

//mysql_*
$id = mysql_insert_id();

//PDO
$pdo = PDO_OBJECT;
$pdo->query();
$id = $pdo->lastInsertId();

//mysqli
$my = MYSQLI_OBJECT;
$my->query();
$id = $my->insert_id;

NOTE: @HopeIHelped's answer is misleading. There is no race condition as long as you are within the same transaction. LAST_INSERT_ID() retrieves the last ID in the given transactions (and the APIs above do as well), so even if you have this file running a ton of transactions and interlocking queries at once, you can use them safely.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405