我有一个PHP搜索。当前,当没有结果显示时,脚本显示并显示错误。当什么都没有返回时,如何使它显示类似“未找到结果”的消息?

<?php
include("incls/connector.php");

$result = mysql_query("SELECT * FROM user WHERE username='$_POST[compName]'");

while($rowval = mysql_fetch_array($result))
    {
        $complainer = $rowval['username'];
        $department = $rowval['department'];
        $phonenumber = $rowval['phone_number'];
    }
        else
    {
        echo 'No Results were found';
    }

    mysql_close()
?>

最佳答案

警告停止使用mysql_ *使用mysqli_ *或PDO
您的代码是错误的,您需要一个if才能使用else

include("incls/connector.php");

$result = mysql_query("SELECT * FROM user WHERE username='".$_POST['compName']."'");//quote for post array

$num_rows = mysql_num_rows($result); //Check for total number of rows

if(is_int($num_rows) && $num_rows >0){
 while($rowval = mysql_fetch_array($result))
    {
        $complainer = $rowval['username'];
        $department = $rowval['department'];
        $phonenumber = $rowval['phone_number'];
    }
  }
else { echo 'No Results were found'; }

mysql_close();

09-17 20:13