PHP + MySQL交易示例 [英] PHP + MySQL transactions examples

查看:59
本文介绍了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 (Exception $e) {
    // An exception has been thrown
    // We must rollback the transaction
    $db->rollback();
}


请注意,根据这种想法,如果查询失败,则必须引发Exception:


Note that, with this idea, if a query fails, an Exception must be thrown:

  • PDO可以做到这一点,具体取决于您的配置方式
    • PDO can do that, depending on how you configure it
      • See PDO::setAttribute
      • and PDO::ATTR_ERRMODE and PDO::ERRMODE_EXCEPTION


      不幸的是,没有涉及魔术.您不能只是在某处放置指令并自动完成事务:您仍然必须指定必须在事务中执行哪些查询组.


      Unfortunately, there is no magic involved. You cannot just put an instruction somewhere and have transactions done automatically: you still have to specific which group of queries must be executed in a transaction.

      例如,在交易之前(在begin之前),您经常会遇到几个查询;在交易之后(在commit之后,则是另外两个查询)或rollback),无论交易发生(或不发生),您都希望执行这些查询.

      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天全站免登陆