通过将数组传递给 MySQL PHP 中的查询来动态创建 OR 条件

2022-01-21 00:00:00 arrays conditional php mysql clause

我正在尝试使用数组动态创建 OR 条件.给定一个数组,当然名称 $courses = array('Eng, 'Deu', 'Bio', 'Chemi') 我想要一个 SQL 查询,它使用数组中的值带有 OR 条件的 AND 子句,例如:

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')

我试图在 PHP MySQL 中做到这一点.

I trying to do it in PHP MySQL.

任何帮助将不胜感激.

提前致谢.

推荐答案

不用那么多 OR 子句,你可以简单地使用 IN(..):

Instead of so many OR clauses, you can simply use IN(..):

SELECT *
FROM classe
WHERE class = 'EFG' AND course IN ('Eng' ,'Deu', 'Bio')

在 PHP 代码中,可以使用 implode() 函数将数组转换为逗号分隔的字符串,并在查询字符串生成中使用.

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.

相关文章