Fixed bracket problem causing sql query to loop