我写了一段关闭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);
?>
此代码的输出是: 答:1 b: 在其他地方
但是在表格中,正在插入第一行。 我用了wamp。 请让我知道我哪里出错了
答案 0 :(得分: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);
}
针对您的具体案例的一些pseude代码:
//TODO: Build up connection, results in $con variable
transactionStart($con);
//TODO: Insert data
if(*all data inserted correctly*){
transactionCommit($con);
} else{
transactionRollback($con);
}
答案 1 :(得分:0)
您需要在发出构成事务的一系列sql命令之前启动事务。
START TRANSACTION
将在SQL中完成。或者你可以使用
$con->autocommit ( false );
$con->begin_transaction();
... transactional SQL statements ...
$con->commit();
干净利落地做到这一点。
PHP + MySQL transactions examples
答案 2 :(得分:0)
我认为您的第二列是varchar
。您的第二个插入语句缺少第二列的引号。
请替换
$a = mysqli_query($con,"INSERT INTO member VALUES (2,'Peter','Peter')");
$b = mysqli_query($con,"INSERT INTO member VALUES (3,'honey','honey')");