Well, what's not working exactly?
Something that caught my eye:
if ($a_row = mysql_fetch_array($query2));
Did you actually mean to put the semicolon there? It's syntactically legal in PHP, but, IMO, if used, could lead to mistakes later on. If I wanted an empty statement, I'd just open and close curly brackets right away, e.g.
if (something) {}
instead of
if (something);
Diego