Moved $query object definition outside of conditional block.

Since there are multiple conditional blocks that may be using this
object, it needs to be defined outside of the first conditional blocks.