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条)

报告相同问题?

悬赏问题

  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题