[英]In transaction insert same key for two tables (1. primary 2. foreign)
I have in this code 2 queries. 我在这段代码中有2个查询。 (in my real code I have 6 queries and I need transaction). (在我的真实代码中,我有6个查询,我需要交易)。
I don't know how to get variable $category_id
cause that category isn't putted yet in database (it should be inserted in same time - all or nothing) 我不知道如何获取变量$category_id
因为该类别尚未放入数据库中(应同时插入-全部或全部不插入)
code: 码:
try {
$this->mysqli->begin_transaction();
$this->mysqli->query("INSERT INTO `category` (`name`) VALUES ('$category')");
$this->mysqli->query("INSERT INTO `subcategory` (`name`,`category_id` ) VALUES ('$subcategory','$category_id')");
$this->mysqli->commit();
}
catch (Exception $e) {
echo $e;
$this->mysqli->rollBack();
}
mysql tables: mysql表:
category:
---------
|id|name|
subcategory:
|id|name|category_id|
So I need some solution how to know before query what is the value of $category_id
, or how to modify query so category_id in database is filed. 所以我需要一些解决方案,在查询之前如何知道$category_id
的值是什么,或者如何修改查询以便在数据库中归档category_id。
LAST_INSERT_ID()
is what you want here. LAST_INSERT_ID()
是您想要的。
try {
$this->mysqli->begin_transaction();
$this->mysqli->query("INSERT INTO `category` (`name`) VALUES ('$category')");
$this->mysqli->query("INSERT INTO `subcategory` (`name`,`category_id` ) VALUES ('$subcategory', LAST_INSERT_ID())");
$this->mysqli->commit();
}
catch (Exception $e) {
echo $e;
$this->mysqli->rollBack();
}
PS Look into prepared statements, instead of concatenating variables into your query. PS查看准备好的语句,而不是将变量连接到查询中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.