dongliaoqiang8524 2015-11-26 15:53
浏览 14
已采纳

PHP Mysql查询返回时如何显示消息没有结果? [重复]

This question already has an answer here:

i just trying to create php form

   <?php 

    $category = $_POST['category'];  
    $length = $_POST['length'];  
    $con = mysql_connect("localhost","globalex","[?H~hS=Oc=ES");
     $db = mysql_select_db("globalex",$con);
     $query = "SELECT list FROM answers WHERE category = '$category' AND length =    '$length'";
    $result = mysql_query($query);
    while($row = mysql_fetch_array($result)) {
    echo 'Category '. $category .' '. $length .' letters: ';
    echo '<b>'. $row['0'].'</b><br>';
    } 
    ?>

how to add message not found when the query has no result? thank you.

</div>
  • 写回答

2条回答 默认 最新

  • dongpu4141 2015-11-26 16:02
    关注

    You shouldn't use the mysql_ functions anymore the are deprecated and don't allow you to use parameterized queries which will prevent you from being SQL injected.

    Here's a way using the mysql_ functions. You can easily transistion this to mysqli or pdo because they both have the num_rows function just check the manual for their implementation.

    $category = mysql_real_escape_string($_POST['category']);  
    $length = mysql_real_escape_string($_POST['length']);  
    $con = mysql_connect("localhost","globalex","[?H~hS=Oc=ES");
     $db = mysql_select_db("globalex",$con);
     $query = "SELECT list FROM answers WHERE category = '$category' AND length =    '$length'";
    $result = mysql_query($query) or die(mysql_error());
    if(mysql_num_rows($result) == 0) {
          echo "No Results";
    } else { 
         while($row = mysql_fetch_array($result)) {
               echo 'Category '. $category .' '. $length .' letters: ';
               echo '<b>'. $row['0'].'</b><br>';
         }
    }
    

    You can read more about SQL injection prevention here, How can I prevent SQL injection in PHP? and more about why the mysql_ functions shouldn't be used here Why shouldn't I use mysql_* functions in PHP?.

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

报告相同问题?

悬赏问题

  • ¥15 表达式必须是可修改的左值
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题