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>";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示