Factor query into prepared parameterized statement and better input check.
(grafted from daa274149925633fb4451bce518231c0efccf894)

--HG--
extra : source : daa274149925633fb4451bce518231c0efccf894