PDO lastinsertId 在事务中返回 0,php - 5.6
Posted
技术标签:
【中文标题】PDO lastinsertId 在事务中返回 0,php - 5.6【英文标题】:PDO lastinsertId is returning 0 in a transaction, php - 5.6 【发布时间】:2017-05-15 18:28:57 【问题描述】:我有一个用 php PDO (5.6) 编写的方法,它应该返回最后插入的 id。 问题是插入已完成,但它返回 0“字符串”。
*** 中有很多帖子都有同样的问题,但我找不到适合我的解决方案。
我错过了什么?
代码如下:
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。这就是我在这里发帖的原因。也许我做错了什么 【参考方案1】:在提交事务之前获取插入 id:
$id = self::$conn->lastInsertId();
self::$conn->commit();
http://www.php.net/manual/en/pdo.lastinsertid.php#85129
【讨论】:
以上是关于PDO lastinsertId 在事务中返回 0,php - 5.6的主要内容,如果未能解决你的问题,请参考以下文章
为啥当我在 mysql 中调用 STORED PROCEDURE 时 pdo->lastInsertId() 返回 0?