views:

33

answers:

1

This might seem ridiculously simple, but I've been getting all kinds of error depending on how I handle a query that returns nothing.

$query = "SELECT * FROM messages WHERE id > ".$messageId;
$result =mysql_query($query);
$time = time();
while(time()-$time<60 && $result==false)
{
    $result = mysql_query($query);
}
if(result != false)
     //Encode response
else
     //return nothing

How do I check whether my mysql_query() returned anything?

+2  A: 

You can check the number of returned rows using mysql_num_rows().

Presuming your loop is to query something until it gets a result, it would be

while(time()-$time<60 && $num_rows == 0)
{
    $result = mysql_query($query);
    $num_rows = mysql_num_rows($result); 

(not sure whether what you're doing here is a really good idea, as it is likely to put a terrible burden on the database server, but that's a different issue)

mysql_query() will return false only on "real" errors, e.g. a misspelled query or lost connection.

Pekka
Also you have to make sure that the MySQL connection didn't time out and that the session is ok. Use mysql_ping for this (although this function can do automatic reconnects, I'd recommend not to use this feature).
svens