I don't really know what is wrong
What's wrong is on two levels. The first problem is, you're not checking the return value of mysql_query() to see if it failed or not. In your case, it is failing, so when you try to use $result it doesn't represent a valid result set.
Do this:
if (! ($result = mysql_query(...)))
echo "Query error: " . mysql_error();
else
{
$r = mysql_fetch_array($result))
...
}
This doesn't solve the ultimate cause of the problem, but it will let you see exactly what mysql doesn't like about your query.