Gagzzz Gagzzz - 1 year ago 134
PHP Question

Hw can I get last inserted id in cakephp 3.x?

I am trying to get last inserted id in cake php 3.



$playlistData = [];
$playlistData["user_id"] = $_POST['user_id'];
$playlistData["play_list_name"] = $_POST['play_list_name'];
$playlistData["section"] = $_POST['section'];
$playlistData["created"] = date('Y-m-d H:i:s', strtotime('now'));
$playlistData["status"] = 'active';
$playlist_en = $this->MyPlaylists->newEntity();
$this->MyPlaylists->patchEntity($playlist_en, $playlistData);

I have also tried:


But it is giving error as below screenshot:
enter image description here

Answer Source

Your code needs some fine tuning.

$playlist_en    =    $this->MyPlaylists->newEntity();  
$playlist_en    =    $this->MyPlaylists->patchEntity($playlist_en, $playlistData);
$isValid        =    $this->MyPlaylists->save($playlist_en);
if ($isValid) {
    $id    =    $playlist_en->id;
    debug($id); // Check your last insert id
} else {
    pr($playlist_en->errors()); // Check errors
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download