PHP + MySQL交易示例 [英] PHP + MySQL transactions examples
问题描述
我真的还没有找到使用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::setAttribute
- ,
PDO::ATTR_ERRMODE
和PDO::ERRMODE_EXCEPTION
- PDO can do that, depending on how you configure it
- See
PDO::setAttribute
- and
PDO::ATTR_ERRMODE
andPDO::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 eithercommit
orrollback
) and you'll want those queries executed no matter what happened (or not) in the transaction.这篇关于PHP + MySQL交易示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- See
- 请参见