pheromix pheromix - 3 months ago 23
MySQL Question

How to get last insert id with Phalcon?

I tried using

LAST_INSERT_ID()
when getting the last id of the autoincrement primary key column but I get EOF exception :

function add($tab) {

$champs= "";
$value = "";
$separateur ="";

$tab["commande_date"] = convertDateFormat5($tab["commande_date"]);

foreach ($tab as $k => $v){
if ($k == "salle_code" || $k == "table_code")
continue;
$champs .= $separateur . $k;
$value .= $separateur . "'" . $v . "'";
$separateur = ",";
}
$champs = '('.$champs.')';
$value = '('.$value.')';
$sSQL = "
INSERT INTO Commande $champs
VALUES $value
";
$query = new Query($sSQL,$this->getDI());

$ret = $query->execute();

$sSQL = "SELECT LAST_INSERT_ID() as last_id";
$queryId = new Query($sSQL,$this->getDI());

return $queryId->execute();

}


So how to get the last id with
Phalcon
?

Answer

you can use the lastInsertId() function

$sSQL = "INSERT INTO Commande $champs VALUES $value ";
$query = new Query($sSQL,$this->getDI());
$ret = $query->execute();
$lastId = $query->lastInsertId();

Update

Here is an example of inserting and getting back the lastinsert id.

$success = $connection->insert(
     "robots",
     array("Astro Boy", 1952),
     array("name", "year")
 );

 //Getting the generated id
 $id = $connection->lastInsertId();

I think this might help you.

Comments