Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last insert id with Phalcon?

Tags:

php

mysql

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 ?

like image 569
pheromix Avatar asked Dec 01 '22 00:12

pheromix


2 Answers

The way you are handling this is fairly anti-MVC and you leave a lot of the Phalcon functionality on the table. You should have a database model named Commande which should be created something like:

$comande = new Commande();

then you can assign values like:

$comande->field1 = "hello";
$comande->adifferentfield = "world";
...

You'd then follow that up with:

$comande->save();  //yes I am aware we should test for success

Then you could access your key field, which would be populated automatically, something like:

print $comande->id;

You're missing out on a lot of the error handling and validation going about it the way you are.

like image 99
Jesse Q Avatar answered Dec 06 '22 08:12

Jesse Q


$yourModel = new YourModel();
$yourModel->save() // Or create();
$newId = $yourModel->getWriteConnection()->lastInsertId();

I think it's easier in this way. Hope it's helpful.

like image 37
X.Herry Avatar answered Dec 06 '22 06:12

X.Herry