我一直在研究交易,据我了解,我的多重插入语句应该可以工作。
我正在使用InnoDB引擎。下面的两个插入语句都可以正常工作,并且可以将数据正确地输入到相应的表中,但前提是我在事务中一次只有一个,而不是两个都在一起。
有人可以告诉我我需要做些什么吗?
失败并显示Affected rows (INSERT): -1
代码:
$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();
答案 0 :(得分:2)
mysqli_query
在一个呼叫中不支持多个查询。您要么需要使用mysqli_multi_query
,要么将查询分为两个单独的对mysqli_query
的调用。由于您正在使用事务,因此将两个呼叫分开会更好,因为很难在mysqli_multi_query
中获得第二个及后续查询的错误信息。