PHPSrike
PHPSrike

Reputation: 33

PHP while loop returning null result

$connect_status = "SELECT connected_to_id FROM tbl_connect WHERE user_id = 
{$_SESSION['user_id']}";

$exec_connstatus_query = mysql_query($connect_status, $db_connect);

while($check_status = mysql_fetch_array($exec_connstatus_query))
{   
  if ($check_status['connected_to_id'] == $profileid)
  {
    echo "{$check_status['connected_to_id']}";
  }
  else
  {
    echo "fail";
  }
}

This code has been troubling me for 3 hours. Here the issue is even if this condition:

if ($check_status['connected_to_id'] == $profileid)

returns false, I am not able to see "fail" when the else statement executes. Any ideas?

Upvotes: 0

Views: 192

Answers (2)

TerryE
TerryE

Reputation: 10888

mysql_query() returns FALSE on error and the loop won't execute at all. This would occur if $_SESSION['user_id'] is not numeric. why not just

$connect_status = "SELECT connected_to_id FROM tbl_connect WHERE user_id ='$_SESSION[user_id]'";

Ditto mysql_fetch_array() returns FALSE if there are no (more) rows. If your session doesn't exist in tbl_connect then the loop won't execute. Don't you want something like:

$connect_status = "SELECT connected_to_id FROM tbl_connect 
                   WHERE user_id ='$_SESSION[user_id]' LIMIT 1";
$exec_connstatus_query = mysql_query($connect_status, $db_connect);
if( ($check_status = mysql_fetch_array($exec_connstatus_query)) && 
    ($check_status['connected_to_id'] == $profileid) ) {
    echo "{$check_status['connected_to_id']}";
} else {
    echo "fail";
}

Upvotes: 1

Nishu Tayal
Nishu Tayal

Reputation: 20830

I would suggest you to check $exec_connstatus_query first, because it may be that your query is not executed properly and thats why control did not go inside while loop. And your response is null. Print $exec_connstatus_query and check first.
Or in case if query return Zero records, in that case loop won't run.

Upvotes: 0

Related Questions