douyue8191 2012-11-30 19:48
浏览 86
已采纳

通过PHP从MySQL数据库中检索行

Please bear with me, I'm new here - and I'm just starting out with PHP. To be honest, this is my first project, so please be merciful. :)

    $row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."'         LIMIT 1"));
    echo $row['message'];

Would this be enough to fetch the message from the database based upon a pre-defined '$code' variable? I have already successfully connected to the database.

This block of code seems to return nothing - just a blank space. :(

I would be grateful of any suggestions and help. :)

UPDATE:

Code now reads:

    <?php
    error_reporting(E_ALL);
   // Start MySQL Connection
    REMOVED FOR SECURITY
    // Check if code exists
    if(mysql_num_rows(mysql_query("SELECT code FROM data WHERE code = '$code'"))){
    echo 'Hooray, that works!';
    $row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code     ."' LIMIT 1")) or die(mysql_error());
    echo $row['message'];
    }
    else {
    echo 'That code could not be found. Please try again!';
    }
    mysql_close();
    ?>
  • 写回答

2条回答 默认 最新

  • doushang2021 2012-11-30 19:57
    关注

    It's best not to chain functions together like this since if the query fails the fetch will also appear to fail and cause an error message that may not actually indicate what the real problem was.

    Also, don't wrap quotes around integer values in your SQL queries.

    if(! $rs = mysql_query("SELECT message FROM data WHERE code = ". (int) $code ." LIMIT 1") ) {
        die('query failed! ' . mysql_error());
    }
    $row = mysql_fetch_array($rs);
    echo $row['message'];
    

    And the standard "don't use mysql_* functions because deprecated blah blah blah"...

    If you're still getting a blank response you might want to check that you're not getting 0 rows returned. Further testing would also include echoing out the query to see if it's formed properly, and running it yourself to see if it's returning the correct data.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题