I have a method written in PHP PDO (5.6) that should return the last inserted id. The issue is that the insertion is accomplished but it returns 0 "string".
There is a lot of posts here in stackoverflow with the same issue, but I could not find a solution for me.
What am I missing?
Here is the code:
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);
}
}
}
Get the insert id before committing your transaction:
$id = self::$conn->lastInsertId();
self::$conn->commit();