Forum Moderators: coopster
I need a little help and I know that what I'm trying to do is among the more simple functions. As my query illustrates below I am trying to check if a variable is present if it isn't I want to echo to that effect. If the value is present and a second condition is also met I want a different echo returned.
$select = mysql_query("SELECT friend, chat FROM chat WHERE friend = '$friend' AND chat = ''");
if (friend == ""){
echo "text=". "{$friend} is offline. ";
}
if (chat == ""){
echo "text=". "{$friend} is online! ";
}else{
echo "text=". "{$friend} is unavailable. ";
}
The problem is I keep getting "friend" is unavailable when I think I should be getting "friend" is offline (I know, I know it amounts to the same thing but I need to distinguish the two)
should be
if ($friend == ""){
and same with chat
if (isset($chat)){
echo "text=". "{$friend} is unavailable. ";
}
Even though there is no value for $chat I still get it's echo statement. Could this have anything to do with how the table row is set in the db? Do I have to have a value of NULL in order to get FALSE as a return for the above statement?
Where do $friend and $chat come from?
The way your query is structured, you'll only get rows that match $friend and have no value in chat. If there's no row with that $friend name OR there is a row but chat is filled in, no rows will be returned.
Are these correct?
Every 'friend' who's online has a row in the table.
If the person is already chatting, the database field 'chat' will contain a value.
If the person is not chatting, the database field 'chat' will be empty.
If the person is not online, no row will be in the table with that friend name
If those four are all correct, see if this makes sense:
$select = mysql_query("SELECT friend, chat FROM chat WHERE friend = '$friend'");
if(mysql_num_rows($select) {
$data = mysql_fetch_assoc($select);
if($data['chat'] == '') {
echo $friend . ' is online! ';
} // EndIf chat is empty
else {
echo $friend . ' is unavailable. ';
} // EndElse chatting
mysql_free_result($select);
} // EndIf have row
else {
echo $friend . ' is offline. ';
} // EndElse don't have row
By dropping chat out of the selection criteria you get a row back if the person is online, then you can check to see whether or not the friend is chatting. If you don't get a row, then it can only be because of one reason - no friend by that name in the table. Yours would work but you'd have to do two queries to determine whether there was no row returned because of no friend or because the friend is chatting.