How to get last insert id with phalcon?

I tried using LAST_INSERT_ID()auto-increment when I get the last column identifier of the primary key, but I get an 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 using Phalcon?

+4
source share
4 answers

you can use function lastInsertId()

$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 returning the lastinsert id.

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

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

I think this may help you.

+3
source

How you handle this is pretty anti-MVC, and you leave many Phalcon features on the table. You should have a database model called Commande, which should be created something like this:

$comande = new Commande();

, :

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

:

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

, , :

print $comande->id;

, .

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

It seems to me that it's easier. Hope this will be helpful.

+3
source

In the controller when saving:

   if ($client->save() == false) {
        foreach ($client->getMessages() as $message) {
            $this->flash->error($message);
        }
        return $this->forward('clients/new');
    }

    // Get new client ID and redirect to new client
    $this->response->redirect("client/page/$client->id");
    $this->view->disable();
0
source

Source: https://habr.com/ru/post/1608676/


All Articles