moved mysql statement to end of loop