I have a Sales Order Master (so_mstr) table and a child table Sales Order Details (sod_det). I am receiving the detail records from $_POST[] array and am preparing the master record inside the script itself. My script is expected to work like following.
- Insert Master Record.
- Insert Detail Records using a PHP
for loop
(a query for each detail record.) - Update another table upon success of Step 1 & 2.
The entire process should roll-back in case any of the steps failed.
I have tried the following code so far. It continues to insert detail records even if master insert query fails. Any idea how to ensure that all the queries run successfully or roll back entirely if any of them fail?
mysqli_autocommit($conn, FALSE);
mysqli_begin_transaction();
$insert_mstr = 'insert into so_mstr(...) values(...)';
mysqli_query($conn, $insert_mstr);
foreach ($order_details['order_details'] as $line_item) {
$insert_line = 'INSERT INTO sod_det(...) values(...)';
mysqli_query($conn, $insert_line);
}
if(mysqli_commit($conn)){
insert_ar_reco(); // inserts into another table
increment_soseq($conn, $param); // updates a table
}
else{
echo 'Error occurred! transaction rolled back.';
}