I have been studying transactions and from what I understand, my multiple insert statement should work.
I'm using InnoDB engine. Both insert statements below work and correctly enters the data into the respective tables, but only if I have one of them at a time in the transaction, not both together.
Can someone tell me what I need to do different?
It fails with Affected rows (INSERT): -1
code:
$con->begin_transaction();
$con->autocommit(FALSE);
$query = "
INSERT INTO `Order` (`PO`,`SellingManagerSalesRecordNumber`,`OrderID`,
`AmountPaid`,`CreatedTime`,`Subtotal`,`Total`,`BuyerUserID`,
`IsMultiLegShipping`,`Status_id`,`SellerUserID_id`)
VALUES
('AF11514','11514','111809902234-1906167668001','55.98',
'2019-01-07 17:42:46','55.98','55.98','hyccas3','false',
(SELECT `id` FROM `Status` WHERE `Status` = 'Completed'),
(SELECT `id` FROM `SellerUserID` WHERE `SellerUserID` = 'afiperformance'))
ON DUPLICATE KEY UPDATE PO = VALUES(PO),
SellingManagerSalesRecordNumber = VALUES(SellingManagerSalesRecordNumber),
OrderID = VALUES(OrderID),
AmountPaid = VALUES(AmountPaid),
CreatedTime = VALUES(CreatedTime), Subtotal = VALUES(Subtotal),
Total = VALUES(Total),
BuyerUserID = VALUES(BuyerUserID),
IsMultiLegShipping = VALUES(IsMultiLegShipping);
INSERT INTO `CheckoutStatus` (`PO`,`LastModifiedTime`,
`PaymentMethod_id`,`Status_id`)
VALUES ('AF11514','2019-01-07 17:47:55',
(SELECT `id` FROM `PaymentMethod` WHERE `PaymentMethod` = 'PayPal'),
(SELECT `id` FROM `Status` WHERE `Status` = 'Complete'))
ON DUPLICATE KEY UPDATE PO = VALUES(PO),
LastModifiedTime = VALUES(LastModifiedTime);";
echo $query;
$con->query($query);
printf("<br><br>\n\nAffected rows (INSERT): %d ", $con->affected_rows) . "\n\n<br><br>";
if ($con->affected_rows == -1) {
echo "<br><br>\n\n Failed " . "\n\n<br><br>";
$con->rollback();
$commit = '';
} else {
$commit = $con->commit();
echo " success " . "\n\n<br><br>";
}
/* commit transaction */
if ($commit == '') {
print("Transaction commit failed\n");
} else {
print("Transaction commit success\n");
}
$con->close();
mysqli_query
doesn't support multiple queries in one call. You either need to use mysqli_multi_query
or split the query into two separate calls to mysqli_query
. Since you are using transactions, splitting into two calls would be better as it is hard to get error information for the second and subsequent queries in mysqli_multi_query
.