download2014711
2016-05-08 05:39
浏览 75
已采纳

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

The following PHP program is to search for a student number in database and display the details if found or give a message if it does not exist.

<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>

If i search for a number which does not exist the else block runs. When i give a number which exists then the if block runs but the while loop does not run. Can anybody help me out? Database field names are correct.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongpochi9741 2016-05-08 05:42
    已采纳

    mysql_query() only returns false if there's an error in the query. Not finding any matching rows is not an error. To tell if any rows were found use 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>";
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题