我正在尝试将数据插入到两个表中,如果插入对其中一个表不起作用,则应该忽略该操作。(我认为这称为事务)
try{
$dbcon=new mysqli($hn,$un,$pw,$dbn);
if($dbcon->connect_error)
throw new Exception($dbcon->connect_error);
$dbcon->autocommit(false);
$query="insert into users(id,email) values(null,'$email')";
$res_a=$dbcon->$query($query);
if($res_a){
$l_id=$res_a->insert_id;
$query="insert into profiles values($l_id,'$name','$birthday')";
$res_b=$dbcon->query($query);
}
if(!res_a || !res_b){
$dbcon->rollback();
throw new Exception("problem with database !!");
}
$dbcon->commit();
}catch(Exception $e){
echo $e->getMessage();
}finaly{
if(isset($dbcon))
$dbcon->close();
}
使用此代码 PHP 显示此错误:“尝试获取非对象的属性”...
换句话说,有没有更好的方法在不使用自动提交方法的情况下进行事务处理(我正在使用 mysqli)?
最佳答案
要回答问题并忽略错误消息的问题,这是如何在一个事务中运行多个更新。
我会尝试使用连接句柄而不是语句句柄来检索 ->insert_id
,因为事务/提交/回滚都是连接句柄的一部分,而不是语句句柄,这似乎是更可靠,可能是您没有收到错误的原因。
$dbcon=new mysqli($hn,$un,$pw,$dbn);
// if no connection can be made there is no point doing anything else
if($dbcon->connect_error) {
echo $dbcon->connect_error;
exit;
}
try{
//$dbcon->autocommit(false);
$dbcon->begin_transaction(); // this does the autocommit = false as well
$query = "insert into users(id,email) values(null,'$email')";
$res_a = $dbcon->$query($query);
if ( ! $res_a ) { // testing for FALSE is only safe way
throw new Exception($dbcon->error);
}
//$l_id = $res_a->insert_id;
$l_id = $dbcon->insert_id;
$query="insert into profiles values($l_id,'$name','$birthday')";
$res_b=$dbcon->query($query);
if( ! res_b) {
throw new Exception($dbcon->error);
}
$dbcon->commit();
}
catch(Exception $e){
echo $e->getMessage();
$dbcon->rollback();
}
finally{ // spelling correction
// not strictly necessary as PHP will close and cleanup automatically
if(isset($dbcon))
$dbcon->close();
}
关于php - 将 commit 设置为 false 后获取最后插入的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34613551/