如何从MYSQL数据库获取最后一个条目? [英] How To Get The Last Entry From MYSQL Database?

查看:136
本文介绍了如何从MYSQL数据库获取最后一个条目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取我输入到数据库中的最后一个ID.这是我使用的代码:

I am trying to get the last id which I entered to my database. Here is the code I use:

$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);
    }

我唯一的输出是确定!".

The only output I have is the 'OK!'.

我该怎么办?

推荐答案

您需要在mysql_fetch_array中使用mysql_query的输出.

You need to use the output of mysql_query in mysql_fetch_array.

$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

Keep in mind that this reads only one row. If you want more use the while loop construction you can find here: http://php.net/mysql_fetch_array

如果您只是进行了INSERT查询,请使用 mysql_insert_id() 获取ID.这是MySQL的功能.可以与AUTO_INCREMENT选项一起使用.

If you just did an INSERT query use mysql_insert_id() to fetch the id. This is a feature of MySQL. This works in conjunction with the AUTO_INCREMENT option.

此外,如果这是您要建立的新站点,请使用mysqli_*函数而不是mysql_*.后者已弃用.

Also, if this is a new site you're building use mysqli_* functions instead of mysql_*. The latter is deprecated.

这篇关于如何从MYSQL数据库获取最后一个条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆