Dynamically creating OR conditions by passing an array to a query in MySQL PHP

会有一股神秘感。 提交于 2019-12-02 09:19:34

问题


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 SQL query that uses the values of the array in its AND clause with OR conditions like:

    SELECT *
        FROM classe
        /* The OR conditions should be created in AND clause using array */
        WHERE class = 'EFG' AND (course = 'Eng' OR course = 'Deu' OR course = 'Bio')

I trying to do it in PHP MySQL.

Any help would be really appreciated.

Thanks in Advance.


回答1:


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.




回答2:


The IN clause will be easier to use than ORs. 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)



来源:https://stackoverflow.com/questions/53400701/dynamically-creating-or-conditions-by-passing-an-array-to-a-query-in-mysql-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!