0

我有一个问题。我似乎无法从我的 MySQL 数据库/表中获取最后插入的记录/ID。我想从“tag_id”列返回最后插入的 id,但我什么也没有得到。顺便说一句,我正在使用 DBO。我尝试了“mysql_insert_id”和“lastInsertId”,但没有成功。

我的数据库表如下所示:

表名:gitags_tags

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

我的 PHP 看起来像这样(在这种情况下,我想返回 '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');

任何帮助深表感谢。

4

4 回答 4

4

您正在使用无效的 Joomla DB 函数,请echo $db->insertid();改用。

于 2014-05-31T13:17:07.857 回答
1

要获取最后插入的记录,您可以使用以下命令:

$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;
于 2013-11-28T12:33:35.267 回答
0

它应该通过使用 DESC 和 LIMIT 回显一个新的 SQL 查询来工作。像这样:

SELECT tag_id FROM gitags_tags ORDER BY tag_id  DESC LIMIT 1
于 2013-11-28T11:10:45.353 回答
-1

确保 tag_id 已设置为主键和增量。

/*
* 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.
于 2013-11-28T11:07:58.977 回答