Skip to content
Advertisement

MySQL Prepared statements with a variable size variable list

How would you write a prepared MySQL statement in PHP that takes a differing number of arguments each time? An example such query is:

JavaScript

The IN clause will have a different number of ids each time it is run.

I have two possible solutions in my mind but want to see if there is a better way.

Possible Solution 1 Make the statement accept 100 variables and fill the rest with dummy values guaranteed not to be in the table; make multiple calls for more than 100 values.

Possible Solution 2 Don’t use a prepared statement; build and run the query checking stringently for possible injection attacks.

Advertisement

Answer

I can think of a couple solutions.

One solution might be to create a temporary table. Do an insert into the table for each parameter that you would have in the in clause. Then do a simple join against your temporary table.

Another method might be to do something like this.

JavaScript

I suspect, but have no proof, that the first solution might be better for larger lists, and the later would work for smaller lists.


To make @orrd happy here is a terse version.

JavaScript

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement