I am trying to create OR condition dynamically using an array. Given an array, of course names $courses = array(\'Eng, \'Deu\', \'Bio\', \'Chemi\')
I want to have a
Instead of so many OR
clauses, you can simply use IN(..):
SELECT *
FROM classe
WHERE class = 'EFG' AND course IN ('Eng' ,'Deu', 'Bio')
In the PHP code, you can use implode() function to convert the array into a comma separated string, and use it in the query string generation.
The IN
clause will be easier to use than OR
s. If you are using PDO you can take advantage of its execute
binding and build the placeholders dynamically then just pass your array to it.
$courses = array('Eng', 'Deu', 'Bio', 'Chemi');
$placeholders = rtrim(str_repeat('?, ', count($courses)), ', ');
$query = "select * from table WHERE class = 'EFG' AND course in ({$placeholders})";
$stmt = $pdo->prepare($query);
$stmt->execute($courses);
Demo: https://3v4l.org/jcFSv (PDO bit non functional)