Reputation: 2495
How would I check to see if the values returned from an sql query are empty? I tried using if(empty($var)), but that didnt work either. heres my code
PHP Code:
while($row = mysql_fetch_array($Result))
{
if(count($row) == 0)
{
....
}
}
How would i check to see if $row is empty?
Upvotes: 5
Views: 48498
Reputation: 100175
if (mysql_num_rows($Result) == 0) {
//error here
} else {
//loop here
}
Gives you a place for an error and a place to work with the results if they are not empty.
Upvotes: 2
Reputation: 96159
The easiest way is to use mysql_num_rows().
$cnt = mysql_num_rows($Result);
if ( 0===$cnt ) {
echo 'no records';
}
else {
while( false!=($row=mysql_fetch_array($Result)) ) {
// ...
}
}
But keep in mind that this function returns the number of records that have been transferred from the MySQL server to the client so far. That's not necessarily the total record count. As long as you're using mysql_query() that's alright. But if you have e.g. large result sets you might want to use mysql_unbuffered_query(), and then you can't rely on mysql_num_rows() (for your purpose), because no records have been transferred before you call mysql_fetch_xyz().
But instead you can use something like
$cnt = 0;
while( false!=($row=mysql_fetch_array($Result)) ) {
$cnt += 1;
// ...
}
if ( 0===$cnt ) {
echo 'no records';
}
Now you have an extra variable as a counter. You might want to avoid that and instead use something like
$row = mysql_fetch_array($Result);
if ( !$row ) {
echo 'no records';
}
else {
do {
// ...
} while( false!=($row=mysql_fetch_array($Result)) ) ;
}
With that approach you don't have an extra variable but some code duplication (the $x=fetch... line).
... make your choice ;-)
Upvotes: 1
Reputation: 2495
This is the right way to do this, you can check if the results are empty by finding number of row in returned results. There is a function in sql to do this mysql_num_rows
. Here is the method to use it:
if (mysql_num_rows($Result) == 0) {
//results are empty, do something here
} else {
while($admin_row = mysql_fetch_array($Result)) {
//processing when you have some data
}
Upvotes: 16