PHP:当条件为true时,While循环不会运行


PHP: While loop does not run when the condition is true

下面的PHP程序将在数据库中搜索学生编号,如果找到,则显示详细信息,如果不存在,则显示消息。

<html>
<body>
<?php
$sno=$_POST['studNo'];
$connection = mysql_connect("localhost", "root", "")
    or die("couldn't connect to the server");
$db = mysql_select_db("student", $connection)
    or die("<b>connection fails");
$query = "select * from performance where Number = '$sno'";
if($result =  mysql_query($query))  
{
    echo "<table border = 1 align = center>";
    echo "<tr>";
    echo "<th>Number<th>Name<th>Address<th>Mobile Number";
    echo "</tr>";
    while($row = mysql_fetch_array($result))
    {           
        echo "<tr>";
        echo "<th>",$row['Number'],"</th>";
        echo "<th>",$row['Name'],"</th>";
        echo "<th>",$row['Address'],"</th>";
        echo "<th>",$row['MobileNo'],"</th>";
        echo "</tr>";
    }
    echo "</table>";
    echo "The student data updated";
}   
else
{
    echo "<b>Customer number does not exist";
}   
mysql_close($connection);
?>
</body>
</html>

如果我搜索一个不存在的数字,则运行else块。当我给出一个存在的数字时,if块会运行,而while循环不会运行。有人能帮我吗?数据库字段名称正确。

mysql_query()仅在查询中出现错误时返回false。找不到任何匹配的行不是错误。要判断是否找到任何行,请使用mysql_num_rows()

$result = mysql_query($query) or die("Query error: " . mysql_error());
if (mysql_num_rows($result) > 0) {
    ...
} else {
    echo "<b>Customer number does not exist</b>";
}