2 ms·
> you need to programmatically construct queries based on user input You still need to build the queries and have control of what parametres are in use. Why no
by qw 4y ago
> you need to programmatically construct queries based on user input
You still need to build the queries and have control of what parametres are in use. Why not build the parameters list dynamically as well?. There are some databases or drivers that have limitations where you need to sanitize data yourself, but I'm not sure if that applies to the majority of the scenarios.
This is a simple example of code for constructing dynamic queries:
query = "... WHERE country = :country";
params.set("country", country);
if (userId != null) {
query += " AND user_id = :userId";
params.set("userId", userId);
}
It may become more complex as you add sub queries or if the database does not support adding a list as a parameter, but the principle is the same. You can always just build the list programatically using parameters instead of concatenating the values given by the user directly.
If there are drivers or databases that does not support this, you will need to sanitize the data yourself of course. But I don't think that is the case for most users.
(btw, database drivers that support named parameters are much more convenient than using "?")