将commit设置为false后获取最后插入的id

时间:2016-01-05 14:04:34

标签: php mysql

我正在尝试将数据插入到两个表中,如果插入不适用于其中一个操作应该被忽略。(我认为这称为事务)

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)?

1 个答案:

答案 0 :(得分:3)

要回答问题并忽略错误消息的问题,这就是如何在事务中运行多个更新。

我会尝试使用连接句柄而不是语句句柄来检索->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();
}