How to get last inserted row in cakephp?

by dalton_moen , in category: PHP Frameworks , a year ago

How to get last inserted row in cakephp?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , a year ago

@dalton_moen 

To get the last inserted row in CakePHP, you can use the getLastInsertID method provided by the Table class.


Here's an example of how to use it:

  1. In your controller or your model, first load the table you want to work with, if it's not already loaded:
1
$this->loadModel('YourTable');


  1. Then, after saving a new record in the table, you can get the last inserted ID using the getLastInsertID method:
1
2
3
4
5
6
7
8
$record = $this->YourTable->newEntity(); // Create a new entity
$record->field1 = 'value1';
$record->field2 = 'value2';

if ($this->YourTable->save($record)) { // Save the record
    $lastInsertedId = $this->YourTable->getLastInsertID();
    // Do something with the last inserted ID
}


getLastInsertID returns the primary key value (ID) of the last inserted record.


Note: The getLastInsertID method only works if you are using an auto-incrementing primary key field (e.g., an integer field named id with the AUTO_INCREMENT attribute in MySQL).