Jump to content

[SOLVED] Help with if else statement


tommyda

Recommended Posts

The following code is giving output if there are results but not if there are no results

 

$q2 = mysql_query("SELECT MAX(bid_amount) as 'maxbid' FROM bids WHERE bid_auction_id = '$auction_id'");
		if (mysql_num_rows($q2) > 0){
			$r2 = mysql_fetch_array($q2);
			echo 
			$r2['maxbid'];}
			else{echo'no';}

 

Can anyone see the problem?

Link to comment
https://forums.phpfreaks.com/topic/143300-solved-help-with-if-else-statement/
Share on other sites

Most likely, the query is for some reason always returning a result even if the WHERE clause is not met, so (mysql_num_rows($q2) > 0) is always true.  However, because the WHERE clause was not met, there is no 'maxbid' in the result and $r2['maxbid'] amounts to nothing.

 

Try the following to test this:

 

echo

$r2['maxbid'].' - Test';

Most likely, the query is for some reason always returning a result even if the WHERE clause is not met, so (mysql_num_rows($q2) > 0) is always true.  However, because the WHERE clause was not met, there is no 'maxbid' in the result and $r2['maxbid'] amounts to nothing.

 

Try the following to test this:

 

echo

$r2['maxbid'].' - Test';

 

Thank you, you were right but how would I avoid this?

The reasoning for that is max will return "0" or nothing always if there is no data to be pulled. You cannot really avoid this, as far as I am aware.

 

Do this instead:

$q2 = mysql_query("SELECT MAX(bid_amount) as 'maxbid' FROM bids WHERE bid_auction_id = '$auction_id'");
         $r2 = mysql_fetch_array($q2);
         if (!empty($r2['maxbid'])) {
                echo $r2['maxbid'] . " - Maxbid";
         }else {
                echo 'There was no max bid for that auction';
        }

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.