PHP + MySQL 事务示例 [英] PHP + MySQL transactions examples

查看:28
本文介绍了PHP + MySQL 事务示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的没有找到使用 MySQL 事务的 PHP 文件的正常示例.你能告诉我一个简单的例子吗?

I really haven't found normal example of PHP file where MySQL transactions are being used. Can you show me simple example of that?

还有一个问题.我已经做了很多编程并且没有使用事务.我可以在 header.php 中放一个 PHP 函数或其他东西,如果一个 mysql_query 失败,那么其他的也会失败吗?

And one more question. I've already done a lot of programming and didn't use transactions. Can I put a PHP function or something in header.php that if one mysql_query fails, then the others fail too?

我想我已经想通了,是吗?:

I think I have figured it out, is it right?:

mysql_query("SET AUTOCOMMIT=0");
mysql_query("START TRANSACTION");

$a1 = mysql_query("INSERT INTO rarara (l_id) VALUES('1')");
$a2 = mysql_query("INSERT INTO rarara (l_id) VALUES('2')");

if ($a1 and $a2) {
    mysql_query("COMMIT");
} else {        
    mysql_query("ROLLBACK");
}

推荐答案

我在处理事务时通常使用的想法如下(半伪代码):

The idea I generally use when working with transactions looks like this (semi-pseudo-code):

try {
    // First of all, let's begin a transaction
    $db->beginTransaction();
    
    // A set of queries; if one fails, an exception should be thrown
    $db->query('first query');
    $db->query('second query');
    $db->query('third query');
    
    // If we arrive here, it means that no exception was thrown
    // i.e. no query has failed, and we can commit the transaction
    $db->commit();
} catch (\Throwable $e) {
    // An exception has been thrown
    // We must rollback the transaction
    $db->rollback();
    throw $e; // but the error must be handled anyway
}


请注意,根据这个想法,如果查询失败,则必须抛出异常:

  • PDO 可以做到这一点,具体取决于您的配置方式
    • 参见PDO::setAttribute
    • PDO::ATTR_ERRMODEPDO::ERRMODE_EXCEPTION
    • 例如,您经常会在事务之前有几个查询(在 begin 之前) 以及在事务之后的另外几个查询 (在 commitrollback) 之后,无论事务中发生什么(或不),您都希望执行这些查询.

      For example, quite often you'll have a couple of queries before the transaction (before the begin) and another couple of queries after the transaction (after either commit or rollback) and you'll want those queries executed no matter what happened (or not) in the transaction.

      这篇关于PHP + MySQL 事务示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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