MySql事务仅在控制台中有效

时间:2017-01-22 02:03:21

标签: php mysql transactions mariadb

当我将其粘贴到MySql控制台

START TRANSACTION;
INSERT INTO `orders` (customer_id) VALUES ('2');
SET @lastid=LAST_INSERT_ID();
INSERT INTO `transactions`
    (order_id,product_id,product_quantity,price,ammount,customer_id)
    VALUES (@lastid,'3','2','4','4','2');
INSERT INTO `transactions`
    (order_id,product_id,product_quantity,price,ammount,customer_id)
    VALUES (@lastid,'1','3','5','4','2');
COMMIT;

它工作正常,当我尝试通过php

做同样的事情
$sql = "START TRANSACTION;";
$sql .="INSERT INTO `orders` (customer_id) VALUES ('$customer_id_form');";
$sql .="SET @lastid=LAST_INSERT_ID();";
foreach ($product_id_form as $key => $product){
$sql .= "INSERT INTO `transactions`
    (order_id,product_id,product_quantity,price,ammount,customer_id) 
    VALUES 
    (@lastid,'$product','$quantity_form[$key]',
        '$price_form[$key]','$amount_form[$key]','$customer_id_form');";
}
$sql .= "COMMIT;";
//$sql = "INSERT INTO products (`product_name`,`curent_price`,`product_quota`) VALUES ('$productname_form','$productprice_form','$productquote_form')";

if ($con->query($sql) === TRUE) {
    echo "New record created successfully";
   header("Location: order.php");
} else {
    echo "Error: " . $sql . "<br>" . $con->error;
}
mysqli_close($con);

它不起作用显示的错误是

  

您的SQL语法有错误;检查手册   对应于您的MariaDB服务器版本,以获得正确的语法   靠近&#39; INSERT INTO orders(customer_id)VALUES(&#39; 2&#39;); SET   @ lastid = LAST_INSERT_ID(); INS&#39;在第1行

2 个答案:

答案 0 :(得分:0)

一次执行一个查询;不要尝试将它们全部发送到服务器。 START ... COMMIT将确定事务语义。

答案 1 :(得分:0)

我认为你需要multi_query来执行多个查询