我有一个用PHP PDO(5.6)编写的方法应该返回最后插入的id。 问题是插入已完成,但它返回0“string”。
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);
}
}
}
答案 0 :(得分:1)
在提交交易之前获取插入ID:
$id = self::$conn->lastInsertId();
self::$conn->commit();