在PHP中,如果我在没有提交的情况下断开连接而不是提交它,我可以让MySQL回滚一个事务吗?

在PHP中,如果我在没有提交的情况下断开连接而不是提交它,我可以让MySQL回滚一个事务吗?

问题描述:

If I run the following PHP, I would expect no value to be inserted into the test table, because I have a transaction that I haven't committed:

$db = mysql_connect("localhost","test","test");
mysql_select_db("test");
mysql_query("begin transaction;");
mysql_query("insert into Test values (1);") or die("insert error: ". mysql_errror());
die('Data should not be commited
');
mysql_query("commit;"); // never occurs because of the die()

But instead it seems to commit anyway. Is there a way to turn off this behaviour without turning off autocommit for the PHP that doesn't use transactions elsewhere on the site?

Edit: This was just a stupid typo. It should be "start transaction" or "begin". Not "begin transaction". Sorry to waste peoples time.

如果我运行以下PHP,我希望没有值插入测试表,因为我有一个 我尚未提交的事务: p>

  $ db = mysql_connect(“localhost”,“test”,“test”); 
mysql_select_db(“test”); 
mysql_query  (“begin transaction;”); 
mysql_query(“insert into Test values(1);”)或die(“insert error:”。mysql_errror()); 
die('Data not not commited 
');  
mysql_query( “提交;”);  //永远不会因为die()
  code>  pre> 
 
 

而发生但反正似乎无论如何都要提交。 有没有办法关闭此行为而不关闭不使用网站上其他地方的事务的PHP的自动提交? p>

编辑:这只是一个愚蠢的错字。 它应该是“开始交易”或“开始”。 不是“开始交易”。 抱歉浪费时间。 p> div>

Use mysql_query('BEGIN'). The SQL "BEGIN TRANSACTION" is not valid (and in fact mysql_query is returning false on that query, which means there is an error). It's not working because you never start a transaction.

The syntax to start a transaction is:

START TRANSACTION

The feature you are talking about is AUTOCOMMIT. If you don't want it, you'll have to disable it:

SET autocommit = 0

The reference can be found at http://dev.mysql.com/doc/refman/5.1/en/commit.html

I also recommend that you test the return value of all mysql_...() functions. You cannot assume that they'll always run successfully.

By default, the transaction will not be rolled back. It is the responsibility of your application code to decide how to handle this error, whether that's trying again, or rolling back.

If you want automatic rollback, that is also explained in the manual:

The current transaction is not rolled back. To have the entire transaction roll back, start the server with the `--innodb_rollback_on_timeout` option.