我真的没有发现正常的PHP文件的例子,MySQL事务正在使用。你能举个简单的例子吗?
还有一个问题。我已经做过很多编程,没有使用过事务。我能不能在header。PHP中放一个PHP函数,如果一个mysql_query失败了,那么其他的也会失败?
我想我已经弄明白了,对吗?:
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");
}
我在处理事务时通常使用的思想是这样的(半伪代码):
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
}
Note that, with this idea, if a query fails, an Exception must be thrown:
PDO可以做到这一点,这取决于您如何配置它
看到PDO:: setAttribute
和PDO::ATTR_ERRMODE和PDO::ERRMODE_EXCEPTION
否则,使用一些其他API,您可能必须测试用于执行查询的函数的结果,并自己抛出异常。
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.
例如,您经常会在事务之前(开始之前)有几个查询,在事务之后(提交或回滚之后)有另外两个查询,您希望无论事务中发生了什么(或没有发生什么),都能执行这些查询。