PDO交易中可以使用哪种代码? [英] What kind of codes can be into PDO transactions?

查看:83
本文介绍了PDO交易中可以使用哪种代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的剧本:

$id    = $_GET['id'];
$value = $_GET['val'];

// database connection here

try{
    $db_conn->beginTransaction();
    // inserting
    $stm1 = $db_conn->prepare("INSERT into table1 (col) VALUES (?)");
    $stm1->execute(array($value));

    // updating
    $stm2 = $db_conn->prepare("UPDATE table2 SET col = "a new row inserted" WHERE id = ?");
    $stm2->execute(array($id));

    $db_conn->commit();
}
catch(PDOException $e){
    $db_conn->rollBack();
}

我想知道的所有内容,我可以在beginTransaction()commit()之间的代码中使用if语句吗?像这样:

All I want to know, can I use an if statement in the codes which are between beginTransaction() and commit() ? Something like this:

$id    = $_GET['id'];
$value = $_GET['val'];

// database connection here

try{
    $db_conn->beginTransaction();
    // inserting
    $stm1 = $db_conn->prepare("INSERT into table1 (col) VALUES (?)");
    $stm1->execute(array($value));

    // updating
    if (/* a condition here */){
        $stm2 = $db_conn->prepare("UPDATE table2 SET col = "a new row inserted" WHERE id = ?");
        $stm2->execute(array($id));
    }

    $db_conn->commit();
}
catch(PDOException $e){
    $db_conn->rollBack();
}

我可以吗?

实际上我问是因为此处是一句话,说你可以这样做很危险:

Actually I asked that because here is a sentence which says you can't and doing that is dangerous:

将不起作用,并且很危险,因为您可能使用嵌套的commit()太早关闭事务.

Won't work and is dangerous since you could close your transaction too early with the nested commit().

推荐答案

您的事务结构没有问题. php.net上的注释仅表示MySQL不支持嵌套事务.为了进一步提出问题,您可以查询任何数据(SQL),操纵数据(DML),但修改任何数据库结构(DDL-数据定义语言).

There is no problem with your transaction structure. The comment on php.net only means, that MySQL does not support nested transactions. In order to your further question, you can query any data (SQL), manipulate data (DML), but not modify any database structures (DDL - data definition language).

/*won't work*/
START TRANSACTION;
/*statement*/
START TRANSACTION; /*nested not supported, auto commit*/
/*statement*/
COMMIT;
/*statement dependend on 1st transaction won't work*/
COMMIT;

另请参见 MySQL参考

事务不能嵌套.这是您发出START TRANSACTION语句或其同义词之一时对任何当前事务执行的隐式提交的结果.

Transactions cannot be nested. This is a consequence of the implicit commit performed for any current transaction when you issue a START TRANSACTION statement or one of its synonyms.

这篇关于PDO交易中可以使用哪种代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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