I have in this code 2 queries. (in my real code I have 6 queries and I need transaction).
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)
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:
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.
LAST_INSERT_ID()
is what you want here.
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();
}
P.S. Look into prepared statements, instead of concatenating variables into your query.