phpmysqlsqljoomladbo

I can't seem to get the last inserted record/id from MySQL


I got a question. I can't seem to get the last inserted record/id from my MySQL database/table. I want to return the last inserted id from the column 'tag_id', but I'm not getting anything back at all. I'm using DBO by the way. I tried both the 'mysql_insert_id' and the 'lastInsertId', but no success.

My database table looks like this:

Table name: gitags_tags

  tag_id  |  name  
----------+---------
   437    |  2011
   438    |  2012
   439    |  2013
   440    |  new

My PHP looks like this (in this case I want to return '440'):

/*
* Insert the new tagname in the database in the table 'gitags_tags'
*/
$query = "INSERT INTO gitags_tags (`name`) VALUES ('".$new_tagname."')";
$db->setQuery($query);

if (!$db->query()) {
    echo "Something went wrong \n";
    echo $query . "\n";
    exit;
}

// Neither of these two work ...
echo mysql_insert_id();
echo $db->lastInsertId('tag_id');

Any help is much appreciated.


Solution

  • To get the last inserted record, you could use this:

    $db = JFactory::getDbo();
    $query = $db->getQuery(true);
    
    $query->select($db->quoteName('tag_id'))
     ->from($db->quoteName('gitags_tags'))
     ->order($db->quoteName('tag_id') . ' DESC');
    
    $db->setQuery($query);
    $result = $db->loadResult();
    
    echo $result;