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

时间:2015-11-26 15:53:47

标签: php mysql

我只想创建php表单

   <?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>';
    } 
    ?>

如何在查询没有结果时添加未找到的邮件? 谢谢。

2 个答案:

答案 0 :(得分:1)

您不应再使用mysql_函数,并且不允许您使用参数化查询来阻止您注入SQL。

这是使用mysql_函数的方法。您可以轻松将此转换为mysqlipdo,因为它们都具有num_rows功能,只需查看手册以了解其实施情况。

$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>';
     }
}

您可以在此处详细了解SQL注入预防,How can I prevent SQL injection in PHP?以及有关为何mysql_函数不应在此使用Why shouldn't I use mysql_* functions in PHP?的原因。

答案 1 :(得分:0)

<?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);
if(mysqli_num_rows($result)>0){
while($row = mysql_fetch_array($result)) {
echo 'Category '. $category .' '. $length .' letters: ';
echo '<b>'. $row['0'].'</b><br>';
} 

}else{
echo 'no result';}
?>