PHP / MySQL - 如何在PDO中使用MySQL BEGIN / COMMIT

时间:2016-10-12 06:02:51

标签: php mysql pdo

我想知道如何在PDO中使用MySQL BEGIN / COMMIT。 我已经读过,最好创建一个插入所有数据的查询,或者根本不插入任何数据以在数据库中提供“一致性” 这是我的代码

$query = $db -> prepare 
                        ("
                        BEGIN;
                        INSERT INTO chat (chat_id,msg,datetime) 
                        VALUES (:cid,:msg,:datetime)
                        INSERT INTO chat_connect (chat_id,sender_id,receiver_id)
                        VALUES (:cid2,:sender_id,:receiver_id);
                        COMMIT;
                        ");
$query -> execute(array(
            "cid" => $cid,
            "msg" => $msg,
            "datetime" => $datetime,
            "sender_id" => $getid,
            "receiver_id" => $frid,
            "cid2" => $cid
            ));

2 个答案:

答案 0 :(得分:0)

您的代码可以正常使用only if emulation mode is turned ON

否则你必须在这样的单独调用中运行查询。

$db->query("BEGIN");
$stmt = $db->prepare("INSERT INTO chat (chat_id,msg,datetime) VALUES (:cid,:msg,:datetime)");
$stmt->execute(...);
$stmt = $db->prepare("INSERT INTO chat_connect (chat_id,sender_id,receiver_id)
                        VALUES (:cid2,:sender_id,:receiver_id)");
$stmt->execute(...);
$db->query("COMMIT");

这是在PHP中运行miltiple-query语句的一般规则。

但是,在事务的情况下,您可以使用their PDO counterparts而不是SQL命令BEGINCOMMIT

答案 1 :(得分:0)

交易语法:

  

开始交易       [transaction_characteristic [,transaction_characteristic] ...]

     

transaction_characteristic:       一致的快照| READ WRITE |只读

     

BEGIN [WORK] COMMIT [WORK] [和[NO] CHAIN] [[NO] RELEASE] ROLLBACK   [WORK] [AND [NO] CHAIN] [[NO] RELEASE] SET autocommit = {0 | 1}

交易示例:

START TRANSACTION;
SELECT @A:=SUM(salary) FROM table1 WHERE type=1;
UPDATE table2 SET summary=@A WHERE type=1;
COMMIT;

取自here

您打算通过PDO创建transaction。这不是一个真正的问题。您可以通过相应地生成查询文本来完成此操作:

$query = $db -> prepare 
                        ("
                        START TRANSACTION;
                        INSERT INTO chat (chat_id,msg,datetime) 
                        VALUES (:cid,:msg,:datetime)
                        INSERT INTO chat_connect (chat_id,sender_id,receiver_id)
                        VALUES (:cid2,:sender_id,:receiver_id);
                        COMMIT;
                        ");
$query -> execute(array(
            "cid" => $cid,
            "msg" => $msg,
            "datetime" => $datetime,
            "sender_id" => $getid,
            "receiver_id" => $frid,
            "cid2" => $cid
            ));

Here您可以看到如何编写防弹交易。