[英]how to insert data into 2 different tables (php mysql)
2 Tables: 2张桌子:
1. BOOKS_IN 1. BOOKS_IN
2. BOOKS_IN_DETAIL 2. BOOKS_IN_DETAIL
BOOKS_in_ID is a primary key and i need BOOKS_in_ID is automatically insert into BOOKS_IN_DETAIL. BOOKS_in_ID是一个主键,我需要BOOKS_in_ID自动插入到BOOKS_IN_DETAIL中。 Here, is it possible to insert records into 2 table using single query?
在这里,是否可以使用单个查询将记录插入到2个表中?
thankyou for your advise. 谢谢您的指教。
You still need two INSERT
statements, but it sounds like you want to get the IDENTITY
from the first insert and use it in the second, in which case, you might want to look into OUTPUT
or OUTPUT INTO
: http://msdn.microsoft.com/en-us/library/ms177564.aspx 您仍然需要两个
INSERT
语句,但是听起来您想从第一个插入中获取IDENTITY
并在第二个插入中使用它,在这种情况下,您可能希望研究OUTPUT
或OUTPUT INTO
: http : //msdn.microsoft .com / zh-CN / library / ms177564.aspx
Src and possible duplicate of: SQL Server: Is it possible to insert into two tables at the same time? Src和以下项的可能重复项: SQL Server:是否可以同时插入两个表中?
You can also use LastInsertId()
for PDO. 您还可以将
LastInsertId()
用于PDO。
A small example: 一个小例子:
$sql = "INSERT INTO city (`city`) VALUES ('Paris') ON DUPLICATE KEY UPDATE `city` = 'Paris";
$dbh->query($sql);
echo $dbh->lastInsertId();
Src: http://php.net/manual/en/pdo.lastinsertid.php Src: http : //php.net/manual/en/pdo.lastinsertid.php
Or get the last insert ID in mysqli: 或者获取mysqli中的最后一个插入ID:
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
Src: http://php.net/manual/en/mysqli.insert-id.php Src: http : //php.net/manual/en/mysqli.insert-id.php
You need to call the appropriate method to get the last inserted id. 您需要调用适当的方法来获取最后插入的ID。
Assuming you use PDO
, you need to call the method lastInsertId. 假设您使用
PDO
,则需要调用方法lastInsertId。 $books_in_id = $pdo->lastInsertId();
If you use mysqli_*
extension that's $books_in_id = $mysqli->insert_id;
如果使用
mysqli_*
扩展名,则$books_in_id = $mysqli->insert_id;
EDIT: if you use the mysql_*
version ( which is deprecated), upgrade first to mysqli_* , or check in the documentation 编辑:如果您使用的是
mysql_*
版本(已弃用),请首先升级到mysqli_ *,或查看文档
Do you have to stick to mysql? 您必须坚持使用mysql吗? Because if you can use mysqli you can use multi_query(), which lets you execute multiple queries at once.
因为如果可以使用mysqli,则可以使用multi_query(),它使您可以一次执行多个查询。
Link : http://php.net/manual/en/mysqli.quickstart.multiple-statement.php 链接: http : //php.net/manual/en/mysqli.quickstart.multiple-statement.php
No,Its not possible with only one INSERT
query. 否,仅使用一个
INSERT
查询是不可能的。
You can follow these steps 您可以按照以下步骤
For point One you can use LAST_INSERT_ID()
function to add foreigh key 对于第一点,您可以使用
LAST_INSERT_ID()
函数添加foreigh键
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.