$db insert, how to get last inserted id?

For Joomla! 2.5 Coding related discussions, please use: http://groups.google.com/group/joomla-dev-general
Note: All 1.6, 1.7 and 3.5 releases have reached end of life and should be updated to 3.x.

Moderator: ooffick

Forum rules
Please use the mailing list here: http://groups.google.com/group/joomla-dev-general rather than this forum.
Locked
User avatar
jomlary
Joomla! Apprentice
Joomla! Apprentice
Posts: 42
Joined: Mon Aug 12, 2013 10:32 am

$db insert, how to get last inserted id?

Post by jomlary » Mon Dec 22, 2014 4:00 pm

My php/sql query is so:

Code: Select all

$db = JFactory::getDbo();
    $insertProjectUser = 'INSERT INTO #__pmanager_user (user_cms_id, user_email, user_created_ip) VALUES (' . $user->id . ', "' . $user->email . '", "' . $_SERVER['REMOTE_ADDR'] . '")';
    $db->setQuery($insertProjectUser );
    $db->query();
$addressID = $db->insertid();

If i do: echo $addressID; i get empty string, not last inserted id, how can i get right result? If i show in database then insert was succesfully.

I need last inserted id because of a new query for another table.

itoctopus
Joomla! Virtuoso
Joomla! Virtuoso
Posts: 4025
Joined: Mon Nov 25, 2013 4:35 pm
Location: Montreal, Canada
Contact:

Re: $db insert, how to get last inserted id?

Post by itoctopus » Tue Dec 30, 2014 12:39 am

This problem has nothing to do with Joomla, but it might be that you don't have persistent connections at your database level.

In any case, insertid() (which uses the last_insert_id ) is dangerous, because if you have a very active site, it might return a different a different ID than the one that you want. You should run a query and get the ID of the row that you just inserted instead of relying on that (unreliable) function.
http://www.itoctopus.com - Joomla consulting at its finest
https://twitter.com/itoctopus - Follow us on Twitter


Locked

Return to “Joomla! 2.5 Coding”