Tuesday, April 24, 2012

Get last inserted row id in Joomla

Ever wanted to get the id of the row that you just inserted to use it for update or any other feature? Well its simple to do it, here is how:

$query = "INSERT INTO #__mytable (name,email) VALUES ('john','john@test.com')";
$db->setQuery( $query );
$db->query();

Once you are done with you insert query simply call the following function:

$lastRowId = $db->insertid();

Works for both Joomla 1.5 and Joomla 2.5

And you will have the inserted row id in the variable. Note that if you remove the $db->query() call from above and then try it will return 0 so just in case if you are wondering it only returns the last value of the table and can have problem if multiple users are working then you don't need to worry as it only returns the id of the row inserted currently.

Edit:
Or if you are using $row->bind() mechanism then you can try the following

$row->bind($data);
$row->store();
$lastRowId = $row->id;

NOTE: You will not get the last inserted row id after you run an update query even though that is not an insertion.

No comments:

Post a Comment