簡體   English   中英

PDO lastinsertId在事務中返回0,PHP-5.6

[英]PDO lastinsertId is returning 0 in a transaction, php - 5.6

我有一個用PHP PDO(5.6)編寫的方法,該方法應返回最后插入的id。 問題是插入已完成,但返回0“字符串”。

在stackoverflow中,有很多帖子都涉及相同的問題,但是我找不到適合我的解決方案。

我想念什么?

這是代碼:

public static function set_values(array $arrSql = NULL) {

        try {            

            $fields="";
            $bindParamStr = "";
            $values = "";
            foreach ($arrSql as $tableName => $arrSetValues) {
                $table=$tableName;                                      //Inside 1 table
                foreach ($arrSetValues as $fieldName => $arrParam) {
                    $fields .= $fieldName.",";                          //Inside 1 field
                    $values .= "?,";
                    $bindParamStr[]=$arrParam;                   
                }
            }
            self::$sql= "INSERT INTO $tableName (".rtrim($fields,",").") VALUES (".rtrim($values,",").")";
            $stmt = self::$conn->prepare(self::$sql);
            $i=1;
            foreach ($bindParamStr as $bindPar) {
               if(count($bindPar)==1){
                   $stmt->bindValue($i,$bindPar[0]);
               } 
               else{
                   $stmt->bindValue($i,$bindPar[0],$bindPar[1]);
               }  
               $i++;
            }  


            self::$conn->beginTransaction();

            if($stmt->execute()){
                self::$conn->commit(); 
                $id= self::$conn->lastInsertId(); 
                return $id;
            }
            else{
                return FALSE;
            }

        } 
        catch (PDOException $e) {

            self::$arrCatchConnResult = self::saveLogMsg(["exceptionObjc"=>$e,"sql"=>self::$sql]);

            $msg = self::$arrCatchConnResult["displayMsgHTML"];

            self::$conn = null;

            if (self::$die) {

                die($msg);
            }
        }
    }

提交事務之前獲取插入ID:

$id = self::$conn->lastInsertId(); 
self::$conn->commit(); 

http://www.php.net/manual/zh/pdo.lastinsertid.php#85129

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM