PHP+MySQL事务示例我真的没有找到使用MySQL事务的PHP文件的正常示例。你能给我举个简单的例子吗?还有一个问题。我已经做了很多编程并且不使用事务。我能把一个PHP函数或者什么东西放进去吗?header.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");}
3 回答
慕田峪9158850
TA贡献1794条经验 获得超7个赞
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();}
PDO可以这样做,这取决于您如何配置它。 看见 和 PDO::ATTR_ERRMODE
和 PDO::ERRMODE_EXCEPTION
否则,使用其他API,您可能需要测试用于执行查询的函数的结果,并亲自抛出异常。
begin
)commit
rollback
)
Cats萌萌
TA贡献1805条经验 获得超9个赞
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");}
炎炎设计
TA贡献1808条经验 获得超4个赞
<?php// trans.phpfunction begin(){ mysql_query("BEGIN");}function commit(){ mysql_query("COMMIT");}function rollback(){ mysql_query("ROLLBACK");}mysql_connect("localhost","Dude1", "SuperSecret") or die(mysql_error()); mysql_select_db("bedrock") or die(mysql_error()); $query = "INSERT INTO employee (ssn,name,phone) values ('123-45-6789','Matt','1-800-555-1212')";begin(); // transaction begins$result = mysql_query($query);if(!$result){ rollback(); // transaction rolls back echo "transaction rolled back"; exit;}else{ commit(); // transaction is committed echo "Database transaction was successful";}?>
添加回答
举报
0/150
提交
取消