[英]MySQL-Query: Refer to last inserted row from another table (just with one php-SQL String)
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?).
有谁知道如何做到这一点(仅使用一个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 ??? ');";
mysql_query cannot execute multiple queries at once, You can use SQL Transactions , for example :- mysql_query不能一次执行多个查询,可以使用SQL Transactions ,例如:
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;");
}
$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. MySQL提供了一个名为LAST_INSERT_ID()的函数,该函数返回当前会话的最后一个auto_increment ID。 http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.