$query might be undef at this point because you don't have a final else clause.