Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top