php - MySQL - 包含多个值

标签 php mysql

我有两个 MySQL 表(规范化),其中包含以下数据:

Customer Type:
+------------------+---------------------+
| customer_type_id |     description     |
|        1         |       customer      |
|        2         |   former customer   |
|        3         |      prospect       |
|        4         | center of influence |
+------------------+---------------------+

Queue:
+----------+------------------+---------+------------+
| queue_id | customer_type_id | user_id | send_date  |
|     1    |         1        |    1    | 2018-02-12 |
|     2    |         1        |    2    | 2018-01-01 |
|     3    |         4        |    1    | 2018-01-01 |
+----------+------------------+---------+------------+

我想查询队列表,但我允许用户筛选多个 customer_type_id 值。我知道我可以在 WHERE 子句中使用多个条件,如下所示:

WHERE
  `user_id` = 1 AND
  (`customer_type_id` = 1 OR
  `customer_type_id` = 4)

但由于我在后端使用 PHP,通过 AJAX 请求发送数据,HTML 标记如下所示:<select name="customers[]"> ,我想知道是否有一种方法可以简单地将 PHP 数组作为参数传递到 SQL 命令中,类似于以下伪代码:

WHERE
  `user_id` = 1 AND
  `customer_type_id` CONTAINS [1, 4]

这样做的原因是我宁愿实现内置的 MySQL 方法,也不愿在运行时构建动态 SQL 命令。

最佳答案

正如其他人所建议的那样,使用 IN () 谓词。它在逻辑上等同于对多个术语使用 OR,如您所示。

参见 https://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html#function_in

但是你应该小心防止SQL注入(inject)。如果您只是使用 PHP implode() 来组合一个不安全的请求参数,您就会面临风险。

您可以 implode() 转换为 int 的值:

$cust_type_list = implode(',', array_map('intval', $_GET['customers']));
$sql = "...WHERE customer_type_id IN ($cust_type_list);

或者您可以使用与数组计数相等的 SQL 查询参数:

$cust_types = (array) $_GET['customers'];
$placeholders = implode(',', array_fill(1, count($cust_types), '?'));
$sql = "...WHERE customer_type_id IN ($placeholders);
$stmt = $pdo->prepare($sql);
$stmt->execute($cust_types);

关于php - MySQL - 包含多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48755733/

相关文章:

php - 从数据库中检索具有特定 ID 的所有帖子

php - Laravel 5 Eloquent 只得到必要的结果

mysql - 获取列中具有连续数字的唯一 ID 列表

mysql - 从表中删除重复行

php - 将.txt文件转换为数组并进行比较

php - SugarCRM 6.5 中的动态下拉菜单故障排除

php - 数字显示很奇怪,不是小数点后两位

php - Require() 和 include() 在 Eclipse 中无法用于代码辅助和自动完成

php - Docker-Compose Wordpress:wp_mail()不起作用

mysql - 在输出 MySQL 中添加列平均值