Sol Sol - 3 months ago 9
PHP Question

How can you insert with PDO then return the `lastInsertId()` in the same function?

How can you insert with PDO then return the

lastInsertId()
that was created? This can be done inside the function, but I either way I would like to get the
lastInsertId()
outside the function.

function insert_PDO($item1, $item2){

$params = array(
":item1" => $item1 ,
":item2" => $item2
);

$sql = "INSERT INTO table (column1, column2)
VALUES (:item1, :item2)
";

//return $this->insert($sql, $params); //this one works

//now trying this, want to return

$insertitems = $this->insert($sql, $params);
$item_ID = $this->lastInsertId();
return ($insertitems, $item_ID) ; //does not work
}

protected function insert($sql, $params)
{
$stmt = $this->dbh->prepare($sql);
return $stmt->execute($params);
}

// I tried this too with the original insert:

$results = $createInsert -> insert_PDO($item1, $item2);
$lastid = $results[0];

foreach($results1 as $row){
$auditVID = $row[ID];
$auditVID = $row[0];
}

Answer

Statement

return ($insertitems, $item_ID) ; 

will cause syntax error.

If you want to return several values - use array:

$insertitems    = $this->insert($sql, $params);  
$item_ID        = $this->lastInsertId();  
return array($insertitems, $item_ID) ;
// or for newer php versions:
return [$insertitems, $item_ID];