You add it to the start of the script.
If you are adding or die to things, it doesn't necessarily mean there's an error. It means that the condition to trigger the or is that equivalent to false. Or die syntax can be added to a mysql_query, but not to a mysql_fetch_*() call for example.
So now you know your problem. Use the information provided by
on the mysql_query to troubleshoot the SQL syntax error. Could be an ambiguity error with the nested subqueries. Which does bring the question on the nested subqueries though, why not just stack on inner joins? Wouldn't that work for what you're doing?
Oh, also. MySQL library is deprecated and will be removed in the future. You should be using the mysqli or pdo libraries instead.