-4

Trying to display a message, when there are no results found.

<?php
mysql_connect ("localhost", "root","")  or die (mysql_error());
mysql_select_db ("test");

$term = $_POST['term'];

$sql = mysql_query("select * from testable where FName like '%$term%' or LName like '%$term%' or ID like '%$term%' ");

while ($row = mysql_fetch_array($sql)) {
    echo '<br/>First Name:'.$row['FName'];
    echo '<br/>Last Name:'.$row['LName'];
    echo '<br/>Phone:'.$row['Phone'];
    echo '<br/><br/>';
}
?>
Manoj Sharma
  • 1,467
  • 2
  • 13
  • 20
  • 1
    The guidelines of how to write answers here clearly insist that you post your code inline in the question. Links to off site resources are _not_ a replacement for that. Please revise your question. Thanks. – arkascha Jan 16 '17 at 22:04
  • mysql_* BAD, security hole in code will get you hacked. –  Jan 16 '17 at 22:07
  • Sorry, Fixed it – Josh Brown Jan 16 '17 at 22:07
  • What's the problem? – takendarkk Jan 16 '17 at 22:10
  • Sidenote: this isn't a live or intended to go live site, is it? – Funk Forty Niner Jan 16 '17 at 22:17
  • 1
    **WARNING**: If you're just learning PHP, please, do not use the [`mysql_query`](http://php.net/manual/en/function.mysql-query.php) interface. It’s so awful and dangerous that it was removed in PHP 7. A replacement like [PDO is not hard to learn](http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/) and a guide like [PHP The Right Way](http://www.phptherightway.com/) explains best practices. Your user data is **not** [properly escaped](http://bobby-tables.com/php.html) and there are [SQL injection bugs](http://bobby-tables.com/) and can be exploited. – tadman Jan 16 '17 at 22:25

2 Answers2

0

Try this :

  if(mysql_num_rows($sql) == 0)
    {
        echo 'No results';
    }
    else
    {
        while($row = mysql_fetch_array($sql))
        {
          //..
        }
    }
Ahmad Mobaraki
  • 7,426
  • 5
  • 48
  • 69
0

You can use mysql_num_rows() function, Which return the number of returned rows.

if( mysql_num_rows($sql) == 0) exit('No records found!');

passing the above condition meaning that there are some result, So you can loop through:

while ($row = mysql_fetch_array($sql)) {
    // print whatever you want.
}
Amir Helmy
  • 121
  • 2
  • 3