dsla94915 2014-07-22 19:26
浏览 207
已采纳

SQL查询在PHP中返回null,但在MySQL中是正确的结果

I'm building a web application for inserting data into a MySQL database. I'm using PHP's PDO API to query the database to obtain an auto-incrementing primary key. When I run the query in MySQL Console, it produces the correct output. But when I try to run the query in PHP, it returns null.

Query:

mysql> SELECT Auto_Increment FROM information_schema.tables WHERE table_name='charlist';

Result in MySQL console:

+----------------+
| Auto_Increment |
+----------------+
|              7 |
+----------------+

Relevant PHP code:

    // Configuration.
    $username = "root";
    $password = "root";
    $hostname = "localhost";
    $dbname = "asoiaf";
    $tablename = "charlist";

    // Opens a connection to the database.
    try {
        $conn = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch(PDOException $e) {
        echo $e->getmessage();
    }

    // Gets all the information from POST.
    $autoidquery = "SELECT Auto_Increment FROM information_schema.tables WHERE table_name='$tablename'";
    $id = $conn->query("SELECT Auto_Increment FROM information_schema.tables WHERE table_name='$tablename'");
    // This should output the auto-incremented primary key, but nothing is output.
    echo $id."<br>Hello world";

Nothing is output on the page, although it should output the auto-incremented id and then "Hello world". I can't see any typos that I've made. Why would the query work in the console, but not in PHP?

  • 写回答

3条回答 默认 最新

  • doudong1117 2014-07-22 19:33
    关注

    You need to fetch the result

    $qry = $conn->query("SELECT Auto_Increment FROM information_schema.tables WHERE  table_name='$tablename'");
    $result = $qry->fetch();
    $id = $result['Auto_Increment'];
    echo $id."<br>Hello world";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?