0

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.

Anirudha Agashe
  • 3,510
  • 2
  • 32
  • 47
Anj Jo
  • 137
  • 2
  • 8
  • why `,$row['Number'],` the string concatenate with `,`? – Murad Hasan May 08 '16 at 05:41
  • @FrayneKonok You can use that, I find it strange to look at myself :) – Dale May 08 '16 at 05:42
  • Warning: Your code is vulnerable to [SQL injection attacks](https://en.wikipedia.org/wiki/SQL_injection). Please read [this post](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) to learn more on how to prevent it. – Pang May 08 '16 at 05:42
  • Warning: The `mysql_*` functions are [no longer supported or maintained](http://stackoverflow.com/questions/12859942). They were [deprecated in PHP 5.5.0](https://wiki.php.net/rfc/mysql_deprecation) and [removed in PHP 7.0.0](http://php.net/manual/en/function.mysql-connect.php#function.mysql-connect-refsynopsisdiv). You are strongly encouraged to migrate to either [MySQLi](http://php.net/manual/en/book.mysqli.php) or [PDO_MySQL](http://php.net/manual/en/ref.pdo-mysql.php). – Pang May 08 '16 at 05:43
  • @FrayneKonok, it's not concatenation. It's a list of arguments for `echo`. – Ruslan Osmanov May 08 '16 at 05:43

1 Answers1

0

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>";
}
Barmar
  • 741,623
  • 53
  • 500
  • 612