1

I have read several of these posts on the site, but still can't find the answer to my problems. I have a while loop where for every entry in the database the table populates. Although if the table in the database is empty, I want it to display a messaged instead. Any ideas of what is wrong here? (aware of the deprecated tags)

$result = mysql_query("SELECT * FROM blog");

while($row = mysql_fetch_array($result))                    
{           
   if(count($row) === 0)
   {
      echo 'No Data';
   }

   <table code>

}
2
  • 1
    However, mysql_* functions are officially deprecated. I recommend you to use PDO or mysqli instead. Commented Jun 9, 2014 at 12:30
  • The problem is that the if is inside the while so it will never be reached Commented Jun 9, 2014 at 12:31

6 Answers 6

3

Use mysql_num_rows for counting rows from DB.

<?php

if (mysql_num_rows($result) > 0) {
    echo '<table>';
    while ($row = mysql_fetch_assoc($result)) {
        echo '<tr>...</tr>';
    }
    echo '</table>';
} else {
    echo 'No result found';
}

?>

EDIT: updated code for table.

Sign up to request clarification or add additional context in comments.

Comments

2
$result = mysql_query("SELECT * FROM blog");

if(mysql_num_rows($result) === 0) {
    echo 'No Data';
} else {
    while($row = mysql_fetch_array($result)) {           
        // code
    }
}

Comments

1

use mysql_num_rows() to get count of query result rows

$rows = mysql_num_rows($result);
if($rows > 0) {
  // do your stuff
}

Comments

1

Use mysql_num_rows for counting number of rows are returned in query.

Comments

1

Try this. mysql_num_rows will check the records in database. On true condition it will allow to execute the while loop other wise else condition will execute.

 $result = mysql_query("SELECT * FROM blog");

    if(mysql_num_rows($result) > 0) {
        echo 'No Result Found';
    } else {
        while($row = mysql_fetch_array($result)) {           
            // Here your Data
        }
    }

Comments

1

If you want to display when no record found then

  $result = mysql_query("SELECT * FROM blog");

  while($row = mysql_fetch_array($result))

  {           
  if(count($row) == 0 || count($row) < 1)
   {
    echo 'No Data';
   }
  else
     {
  //print records

      }
  } 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.