PHP:当条件为真时,循环不运行

时间:2016-05-08 05:39:48

标签: php

以下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循环不运行。有人可以帮帮我吗?数据库字段名称是正确的。

1 个答案:

答案 0 :(得分:0)

如果查询中出现错误,则

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>";
}