0

I want to put a new row into the database AND refer to this row in a second table. Does anyone have an idea how to do it (using just one php: mysql_query?).

Starting two queries for this purpose is too risky, because the connection can be lost between them.

Idea:

$sql ="INSERT INTO `tbl_humpahumpa`(`humpa_txt`) VALUES ('Ring Ring Ring Bananafon!'); 
INSERT INTO `tbl_reference_to_humpa`(`humpa_ref_id`) VALUES (' ??? referenceid ??? ');";
John Pixel
  • 57
  • 1
  • 8

2 Answers2

0
$sql = "INSERT INTO `tbl_humpahumpa`(`humpa_txt`) VALUES ('Ring Ring Ring Bananafon!');
INSERT INTO `tbl_reference_to_humpa`(`humpa_ref_id`) VALUES (LAST_INSERT_ID());"; // Done

MySQL provides a function called LAST_INSERT_ID() that returns the last auto_increment ID for the current session. http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id

John Pixel
  • 57
  • 1
  • 8
Naomi
  • 389
  • 4
  • 11
0

mysql_query cannot execute multiple queries at once, You can use SQL Transactions, for example :-

try{
  mysql_query("START TRANSACTION");
  mysql_query("INSERT INTO `tbl_humpahumpa`(`humpa_txt`) VALUES ('Ring Ring Ring Bananafon!')");
  mysql_query("INSERT INTO `tbl_reference_to_humpa`(`humpa_ref_id`) VALUES ('".mysqli_insert_id()."')");
  mysql_query("COMMIT;")
} catch (Exception $e) {
  mysql_query("ROLLBACK;");
}

or mysqli_multi_query

kamal pal
  • 4,187
  • 5
  • 25
  • 40