【问题标题】:PDO lastinsertId is returning 0 in a transaction, php - 5.6PDO lastinsertId 在事务中返回 0,php - 5.6
【发布时间】:2017-05-15 18:28:57
【问题描述】:

我有一个用 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);
            }
        }
    }

【问题讨论】:

  • 您的行是否被插入并且它有一个 auto_incrementing id 列?
  • 是的。插入没问题。
  • 嘿 Ryan,我看到了您发送的帖子,但我的方案不适合任何两种可能的解决方案。我只有 1 个连接,并且我有一个自动增量 ID。这就是我在这里发帖的原因。也许我做错了什么

标签: php pdo lastinsertid


【解决方案1】:

在提交事务之前获取插入 id:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 2020-10-30
    • 2012-07-31
    • 1970-01-01
    • 2022-12-19
    • 1970-01-01
    相关资源
    最近更新 更多