Anj Jo Anj Jo - 6 months ago 10
PHP Question

PHP: Whie loop deos not run when the condition is true

The following PHP program is to search for a stuedent 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.

Answer

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