我正在尝试获取我输入数据库的最后一个 ID。这是我使用的代码:
$test_query = "SELECT * FROM table ORDER BY id DESC LIMIT 1";
if ( mysql_query($test_query) ) {
echo 'OK!';
$results = mysql_fetch_array($test_query);
echo $results['id'];
print_r ($results);
}
我唯一的输出是“OK!”。
我做错了什么?
最佳答案
您需要在mysql_fetch_array
中使用mysql_query
的输出。
$res = mysql_query($test_query);
if ($res === false) {
throw new Exception("query failed");
}
$row = mysql_fetch_array($res);
echo $row["id"];
请记住,这仅读取一行行。如果您想更多地使用 while
循环结构,您可以在这里找到:http://php.net/mysql_fetch_array
如果您刚刚执行了 INSERT
查询,请使用 mysql_insert_id()
获取 id。这是MySQL的一个特性。这与 AUTO_INCRMENT
选项结合使用。
此外,如果这是您正在构建的新站点,请使用 mysqli_*
函数而不是 mysql_*
。后者已被弃用。
关于php - 如何从 MYSQL 数据库获取最后一条记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23065680/