Refactored code in query.php, added comments