in reply to database selecting then validating
poj’s response incorporates the basic ideas here, whether or not this is exactly the strategy you want to use in your particular case. There are, natcherly, several ways to do it. But the most important feature of all of them is that all of the user-provided values are presented to the SQL query by means of placeholders, which are the (notice, not-quoted) question marks.
Incidentally, if you do this a lot (say, tens of thousands of times...) you can save a perhaps-significant amount of time by “preparing” the query once, obtaining a “statement handle,” which you then use to execute the same query (substituting different input-values for the placeholders each time). You will never, ever have a “Bobby Tables problem” because the user-provided input is never regarded as “part of” the SQL that is to be executed: it is, as it were, an input-variable.