douliu1092 2014-04-14 16:46
浏览 147

如何从MYSQL数据库获取最后一个条目?

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!'.

What do i do wrong?

  • 写回答

2条回答 默认 最新

  • doyhq66282 2014-04-14 16:49
    关注

    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"];
    

    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


    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.


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

    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程