通过将数组传递给 MySQL PHP 中的查询来动态创建 OR 条件 [英] Dynamically creating OR conditions by passing an array to a query in MySQL PHP

查看:51
本文介绍了通过将数组传递给 MySQL PHP 中的查询来动态创建 OR 条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用数组动态创建 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.

这篇关于通过将数组传递给 MySQL PHP 中的查询来动态创建 OR 条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆