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:
You may have table texts
(T_ID (int), T_TEXT (text))
and table test
(id (int), var (varchar(255)))
In insert into test values (1, '1,2,3') ;
the following will output rows from table texts where T_ID IN (1,2,3)
:
SELECT * FROM `texts` WHERE (SELECT FIND_IN_SET( T_ID, ( SELECT var FROM test WHERE id =1 ) ) AS tm) >0
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.
Safer.
$galleries = array(1,2,5);
array_walk($galleries , 'intval');
$ids = implode(',', $galleries);
$sql = "SELECT * FROM galleries WHERE id IN ($ids)";
As Flavius Stef's answer, you can use intval()
to make sure all id
are int values:
$ids = join(',', array_map('intval', $galleries));
$sql = "SELECT * FROM galleries WHERE id IN ($ids)";
Safe way without PDO:
$ids = array_filter(array_unique(array_map('intval', (array)$ids)));
if ($ids) {
$query = 'SELECT * FROM `galleries` WHERE `id` IN ('.implode(',', $ids).');';
}
(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 selectionUse:
select id from galleries where id in (1, 2, 5);
A simple for each
loop will work.
Flavius/AvatarKava's way is better, but make sure that none of the array values contain commas.
Besides using the IN query, you have two options to do so as in an IN query there is a risk of an SQL injection vulnerability. You can use looping to get the exact data you want or you can use the query with OR case
1. SELECT *
FROM galleries WHERE id=1 or id=2 or id=5;
2. $ids = array(1, 2, 5);
foreach ($ids as $id) {
$data[] = SELECT *
FROM galleries WHERE id= $id;
}