我有一个用PHP (5.6)编写的方法,它应该返回最后插入的id。问题是插入已完成,但它返回0 "string“。
这里有很多关于相同问题的堆叠溢出的帖子,但我无法为自己找到解决方案。
我遗漏了什么?
以下是代码:
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);
}
}
}发布于 2017-05-15 18:40:12
在提交事务之前获取insert id:
$id = self::$conn->lastInsertId();
self::$conn->commit(); http://www.php.net/manual/en/pdo.lastinsertid.php#85129
https://stackoverflow.com/questions/43986452
复制相似问题