Given an array of ids $galleries = array(1,2,5)
I want to have a SQL query that uses the values of the array in its WHERE clause like:
SELECT *
FROM galleries
WHERE id = /* values of array $galleries... eg. (1 || 2 || 5) */
How can I generate this query string to use with MySQL?
Below is the method I have used, using PDO with named placeholders for other data. To overcome SQL injection I am filtering the array to accept only the values that are integers and rejecting all others.
Safer.
You may have table
texts
(T_ID (int), T_TEXT (text))
and tabletest
(id (int), var (varchar(255)))
In
insert into test values (1, '1,2,3') ;
the following will output rows from table texts whereT_ID IN (1,2,3)
:This way you can manage a simple n2m database relation without an extra table and using only SQL without the need to use PHP or some other programming language.
Basic methods to prevent SQL injection are:
Using prepared statements and parameterized queries query is considered the better practice, but if you choose the escaping characters method then you can try my example below.
You can generate the queries by using
array_map
to add a single quote to each of elements in the$galleries
:The generated $sql var will be:
For MySQLi with an escape function:
For PDO with prepared statement:
Safe way without PDO:
(array)$ids
Cast$ids
variable to arrayarray_map
Transform all array values into integersarray_unique
Remove repeated valuesarray_filter
Remove zero valuesimplode
Join all values to IN selection