简体   繁体   中英

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.

You're using an invalid Joomla DB function, use echo $db->insertid(); instead.

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;

It should work by echoing a new SQL query with DESC and LIMIT. Like this:

SELECT tag_id FROM gitags_tags ORDER BY tag_id  DESC LIMIT 1

make sure the tag_id has set as primary key and increment as well.

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

echo mysql_insert_id();
echo $db->lastInsertId('tag_id');

//Use select query and echo this record with this tag_id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM