繁体   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