1

最近我一直在创建一个函数来记录数据库中的每一个变化,我只是将它记录到一个表中。

表backup_log:backupTableName、backupLastUpdate、backupLastupload

因此,每次更改时,都会将日期记录到“backup_log”中。它运行良好,但是当我需要 Last Insert Id 时遇到问题,我使用 $orderid =$dbh->lastInsertId('orderId');来获取“last insert Id”,但它返回“0”。我发现当我放置querylog()运行另一个查询的函数而该query()函数仍在运行时,问题就出现了。因为它使用相同的 PDO 对象。那么,有什么建议让我能够在运行时获得“最后插入 id”querylog()吗?

这是我的代码:

//$dbh is object of PDO connection

$sql = query("INSER INTO orders ...");
$orderid = $dbh->lastInsertId('orderId'); // table "orders"

function query($sql){
    #this function is not the full version, just for example
    global $dbh;
    $query=$dbh->exec($sql);

    querylog($sql); // Log every insert, delete and update query
}   

function querylog($sql){  
    global $dbh; // PDO object
    global $now;

    //Table backup_log: backupTable, backupLastUpdate, backupLastupload

    ###### Log: for insert and update ########
    #if the query too long, cut for 200 chars and convert them to array
    $sql_clean_space=str_replace(array("  ",'`'),array(" ",''),$sql); //change double space to single space
    if(strlen($sql_clean_space) > 200){
        $sql_clean_space = substr($sql_clean_space, 0, 200); // get only 200 char
    }

    $sql_array=explode(" ", $sql_clean_space); //convert to array to get the command name, insert or update
    $now_date=$now;

    #save log
    if(strtolower($sql_array[0])=='insert' or strtolower($sql_array[0])=='delete'){
        #check whether the query is insert or update
        $sqlx = "SELECT * FROM backup_log WHERE backupTable='".$sql_array[2]."'";
        $query=$dbh->query($sqlx);  
        $check_row=$query->rowCount($query);

        if($check_row){
            $sql_log="UPDATE backup_log SET backupLastUpdate='$now' WHERE backupTable='". $sql_array[2] . "'";
        }else{
            $sql_log="INSERT INTO backup_log VALUES('".$sql_array[2]."', '$now_date','$now_date')";
        } 
    }elseif(strtolower($sql_array[0])=='update'){
        $sqlx = "SELECT * FROM backup_log WHERE backupTable='".$sql_array[1]."'";
        $query=$dbh->query($sqlx);  
        $check_row=$query->rowCount($query);

        if($check_row){ 
            $sql_log="UPDATE backup_log SET backupLastUpdate='$now' WHERE backupTable='". $sql_array[1] . "'";
            }else{
            $sql_log="INSERT INTO backup_log VALUES('".$sql_array[1]."', '$now_date','$now_date')";
        }
    }
    $query_log=$dbh->exec($sql_log);
    ####### End of log ######################
}
4

1 回答 1

1

也许您可以在查询函数中分配最后一个插入 id,并且可以在查询执行时保留它。请参阅下面的代码;

$sql = query("INSER INTO orders ...", 'orderId'); //$sql is equal to last insert id 
$orderid = $sql

function query($sql, $specific_id_column){
    #this function is not the full version, just for example
    global $dbh;
    $query=$dbh->exec($sql);
    $last_id = $dbh->lastInsertId($specific_id_column);
    querylog($sql); // Log every insert, delete and update query
    return $last_id;
} 
于 2014-01-23T07:30:54.713 回答