I feel like this should probably use the URI class to set the query, which I think takes care of a lot of this work for you.  I *think*.  If it doesn't, tell me so I don't make that mistake again. :)