简体   繁体   中英

How would I check if values returned from an SQL/PHP query are empty?

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?

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 
}  
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.

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 eg 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 ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM