1

With the following PHP code, how do i check if there's no row retuned so i can echo some message?

PHP:

<?php 
    require_once 'db_conx.php';
    $Result = mysql_query("SELECT * FROM ads WHERE pid = '2'")
        or die (mysql_error());
    while($row = mysql_fetch_array($Result)){
        echo '<span class="classPid" style="display:none">'.$row['pid'].'</span>';
    }
?>

Thanks

Pascal
  • 1,288
  • 8
  • 13
Relm
  • 7,923
  • 18
  • 66
  • 113
  • possible duplicate of [PHP and MySQL: Number of rows returned](http://stackoverflow.com/questions/5140298/php-and-mysql-number-of-rows-returned) – Matsemann Dec 08 '13 at 10:03

2 Answers2

3

There are a number of ways to do this. There is a specific function mysql_num_rows() which will return the number of rows returned.

mysql_num_rows($Result);

This will return 0 if there are no rows affected or returned.

You could also create some conditions using mysql_fetch_array. mysql_fetch_array will return FALSE if there are no rows.

On a separate note it would be a good idea to update your connection and functions to mysqli as mysql is no depreciated.

See docs on mysql_num_rows().

http://www.php.net/mysql_num_rows

Dane Caswell
  • 201
  • 5
  • 9
  • 2
    That's a good answer too, but you know the JQuery generation always goes for short solutions. – Relm Dec 08 '13 at 15:45
  • This is the best approach but mysql_num_rows($Result); has been deprecated and removed since PHP 7.0 Instead use: mysqli_num_rows() OR mysqli_stmt_num_rows() OR PDOStatement::rowCount() See the linked PHP documents for details. @Dane Caswell, I'll leave any editing to you. Due to SOs SEO this answer is still a top Google hit. – Shaedo Oct 21 '19 at 06:07
2

Something like this

<?php 
    require_once 'db_conx.php';
    $Result = mysql_query("SELECT * FROM ads WHERE pid = '2'")
        or die (mysql_error());
    $i=0;
    while($row = mysql_fetch_array($Result)){
        echo "<span class='classPid' style='display:none'>".$row['pid']."</span>";
        $i++;
    }
    if($i==0){
        echo "No rows found";
    }
?>
Jaak Kütt
  • 2,566
  • 4
  • 31
  • 39
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126