I have a question about mySql queries which i use PHP to make -
In my code i insert data to table - main_query . if the insert part want well i do second insert query - sub_query.
How do i cancel the first insert query if the second was failed? I mean - is it possible to send both queries to be checked before i actually execute them? or - is it possible to do rollback for the first "main_query" query?
$main_query = "INSERT INTO table_1 (...) VALUES (...)";
$res = $conn->query($main_query);
if ($res)
{
$id = mysqli_insert_id($conn);
$sub_query = "INSERT INTO table_2 (...) VALUES (...)"; // use var "id" here
$res = $conn->query($sub_query);
}
In this case you need to use transactions and rollback:
# start mysql transaction
mysqli_begin_transaction($conn, MYSQLI_TRANS_START_READ_WRITE);
$main_query = "INSERT INTO table_1 (...) VALUES (...)";
$res = mysqli_query($conn, $main_query);
if ($res)
{
$id = mysqli_insert_id($conn);
$sub_query = "INSERT INTO table_2 (...) VALUES (...)"; // use var "id" here
$res = mysqli_query($conn, $sub_query);
if ($res) {
# both inserts succeed - do commit
mysqli_commit($conn);
}
else {
# second insert fail - do rollback
mysqli_rollback($conn);
}
} else {
# first insert fail - do rollback
mysqli_rollback($conn);
}
or we can use object oriented style like:
# start mysql transaction
$mysqli->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
$main_query = "INSERT INTO table_1 (...) VALUES (...)";
$res = $mysqli->query($main_query);
if ($res)
{
$id = $mysqli->insert_id;
$sub_query = "INSERT INTO table_2 (...) VALUES (...)"; // use var "id" here
$res = $mysqli->query($sub_query);
if ($res) {
# both inserts succeed - do commit
$mysqli->commit();
}
else {
# second insert fail - do rollback
$mysqli->rollback();
}
} else {
# first insert fail - do rollback
$mysqli->rollback();
}
Look working example here PHPize.online