PHP/MySQL - 如何在 PDO 中使用 MySQL BEGIN/COMMIT [英] PHP/MySQL - How to use MySQL BEGIN/COMMIT with PDO

查看:37
本文介绍了PHP/MySQL - 如何在 PDO 中使用 MySQL BEGIN/COMMIT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何使用带有 PDO 的 MySQL BEGIN/COMMIT.我读过最好创建一个查询,要么插入所有数据,要么根本不插入,以在数据库中提供一致性"这是我的代码

I was wondering how to use a MySQL BEGIN/COMMIT with a PDO. I've read that it's best to create a query that either inserts all data or none at all to provide 'consistency' in the database Here's my code

$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
            ));

推荐答案

事务语法:

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

START TRANSACTION [transaction_characteristic [, transaction_characteristic] ...]

交易特征:具有一致的快照 |读 写 |只读

transaction_characteristic: WITH CONSISTENT SNAPSHOT | READ WRITE | READ ONLY

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

BEGIN [WORK] COMMIT [WORK] [AND [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;

取自此处.

您打算通过 PDO 创建一个事务.这不是真正的问题.您可以通过相应地生成查询文本来实现:

You intend to create a transaction via PDO. That is not really a problem. You can do it by generating the query text accordingly:

$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 you can see how you can write a bullet-proof transaction.

这篇关于PHP/MySQL - 如何在 PDO 中使用 MySQL BEGIN/COMMIT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆