Let PHP tell you what is wrong. Check the return value from the query function. If it is false, use mysql_query() to log the error (or just echo it for now while debugging). I find it useful to put the query into a string before using it, so that the debug info can include the entire query exactly as sent to the DB, too.
$query = "SELECT blah blah blah...";
$result = mysql_query($query);
if($result == false)
{
user_error(mysql_error() . "<br />\n$query");
die("DB error");
}
while(blah blah blah) . . .