added database query, some rearranging in main and ad.php