2

我写了一个代码来关闭 AutoCommit :

<?php 
$con = mysqli_connect("localhost","root","","databases");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(mysqli_query($con,"SET autocommit=0")){//tried using mysqli_autocommit($con,FALSE);

// Insert some values 
$a=mysqli_query($con,"INSERT INTO member VALUES (2,'Peter','Peter')");
$b=mysqli_query($con,"INSERT INTO member VALUES (3,honey,'honey')");
echo "a:";
echo $a;
echo "b:";
echo $b;
if($a&&$b){
mysqli_query($con,"COMMIT");//tried using mysqli_commit($con);
echo "in if";
}
else{
mysqli_query($con,"ROLLBACK");//tried using mysqli_rollback($con);
echo "in else";
}
}
mysqli_close($con);
?>

此代码的输出是:a:1 b: in else

但在表中,第一行被插入。我为此使用了 wamp。请让我知道我哪里出错了

4

3 回答 3

0

我认为您的第二列是varchar. 您的第二个插入语句缺少第二列的引号。请替换插入查询,如

$a = mysqli_query($con,"INSERT INTO member VALUES (2,'Peter','Peter')");
$b = mysqli_query($con,"INSERT INTO member VALUES (3,'honey','honey')");
于 2015-04-20T11:34:32.183 回答
0

您需要在发出一系列构成事务的 sql 命令之前启动事务。

 START TRANSACTION

将在 SQL 中完成。或者你可以使用

$con->autocommit ( false );
$con->begin_transaction(); 
... transactional SQL statements ...
$con->commit();

干净地做到这一点。

PHP + MySQL 事务示例

@Sylvain Leroux 是对的!如果您使用的是 MyISAM,您可以发出任何您想要的事务命令,但它们仍然无法工作。事务支持在 InnoDB 中。

于 2013-08-14T16:26:34.683 回答
0

我将这个函数用于事务启动、提交和回滚:

function transactionStart($dbConnection){
    return $dbConnection->autocommit(false);
}
function transactionCommit($dbConnection) {
    $dbConnection->commit();
    return  $dbConnection->autocommit(true);
}
function transactionRollback($dbConnection) {
     $dbConnection->rollback();
     return $dbConnection->autocommit(true);
}

针对您的特定情况的一些伪代码:

//TODO: Build up connection, results in $con variable
transactionStart($con);
//TODO: Insert data
if(*all data inserted correctly*){
  transactionCommit($con);
} else{
  transactionRollback($con);
}
于 2013-08-14T16:21:53.873 回答