added if statement to query loop