7

我的平台:

PHP 和 mySQL

我的情况:

我正在尝试在我的代码中实现事务。我试图按照示例进行操作,但这并没有太大帮助。我正在运行 3 个查询,并且我想以这样的方式编写事务,以便如果任何查询失败,整个事务都应该回滚。我真的很感激一个简单、高效和非面向对象的 PHP 代码来实现这个目标。先感谢您。

我的 PHP 代码:

//db_res calls a custom function that performs a mysql_query on the query
$res1 = db_res("SELECT c1, c2 FROM t1 WHERE c5 = 3");
$res2 = db_res("UPDATE t2 SET c1 = 5 WHERE c2 = 10");
$res3 = db_res("DELETE FROM t3 WHERE c1 = 20");

if( $res1 && $res2 && $res3 )
{
 //commit --- but how?
}
else
{
 //rollback --- but how?
}
4

2 回答 2

18

你不需要使用 mysqli。您可以将事务命令作为查询发出。

所以对于你的例子:

mysql_query("start transaction;");

//db_res calls a custom function that performs a mysql_query on the query
$res1 = db_res("SELECT c1, c2 FROM t1 WHERE c5 = 3");
$res2 = db_res("UPDATE t2 SET c1 = 5 WHERE c2 = 10");
$res3 = db_res("DELETE FROM t3 WHERE c1 = 20");

if( $res1 && $res2 && $res3 )
{
  mysql_query("commit;");
}
else
{
  mysql_query("rollback;");
}

顺便说一句,如果您正在考虑升级到 mysqli,请不要。而是升级到 PDO,它更加理智。

于 2010-10-25T15:46:57.883 回答
8

您需要使用mysqli 扩展来使用此功能。

请参阅:autocommit()commit()rollback()

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* disable autocommit */
mysqli_autocommit($link, FALSE);

mysqli_query($link, "CREATE TABLE myCity LIKE City");
mysqli_query($link, "ALTER TABLE myCity Type=InnoDB");
mysqli_query($link, "INSERT INTO myCity SELECT * FROM City LIMIT 50");

/* commit insert */
mysqli_commit($link);

/* delete all rows */
mysqli_query($link, "DELETE FROM myCity");

if ($result = mysqli_query($link, "SELECT COUNT(*) FROM myCity")) {
    $row = mysqli_fetch_row($result);
    printf("%d rows in table myCity.\n", $row[0]);
    /* Free result */
    mysqli_free_result($result);
}

/* Rollback */
mysqli_rollback($link);

if ($result = mysqli_query($link, "SELECT COUNT(*) FROM myCity")) {
    $row = mysqli_fetch_row($result);
    printf("%d rows in table myCity (after rollback).\n", $row[0]);
    /* Free result */
    mysqli_free_result($result);
}

/* Drop table myCity */
mysqli_query($link, "DROP TABLE myCity");

mysqli_close($link);
?>
于 2010-01-25T15:06:56.120 回答