本文翻译自:Passing an array to a query using a WHERE clause

Given an array of ids $galleries = array(1,2,5) I want to have a SQL query that uses the values of the array in its WHERE clause like: 给定一个ID数组$galleries = array(1,2,5)我想拥有一个SQL查询,该查询使用WHERE子句中的数组值,例如:

SELECT *
FROM galleries
WHERE id = /* values of array $galleries... eg. (1 || 2 || 5) */

How can I generate this query string to use with MySQL? 如何生成此查询字符串以用于MySQL?


#1楼

参考:https://stackoom.com/question/3oA2/使用WHERE子句将数组传递给查询


#2楼

Using PDO: [1] 使用PDO: [1]

$in = join(',', array_fill(0, count($ids), '?'));
$select = <<<SQLSELECT *FROM galleriesWHERE id IN ($in);
SQL;
$statement = $pdo->prepare($select);
$statement->execute($ids);

Using MySQLi [2] 使用MySQLi [2]

$in = join(',', array_fill(0, count($ids), '?'));
$select = <<<SQLSELECT *FROM galleriesWHERE id IN ($in);
SQL;
$statement = $mysqli->prepare($select);
$statement->bind_param(str_repeat('i', count($ids)), ...$ids);
$statement->execute();
$result = $statement->get_result();

Explanation: 说明:

Use the SQL IN() operator to check if a value exists in a given list. 使用SQL IN()运算符检查给定列表中是否存在值。

In general it looks like this: 一般来说,它看起来像这样:

expr IN (value,...)

We can build an expression to place inside the () from our array. 我们可以构建一个表达式以放置在数组中的()内。 Note that there must be at least one value inside the parenthesis or MySQL will return an error; 请注意,圆括号内必须至少有一个值,否则MySQL将返回错误。 this equates to making sure that our input array has at least one value. 这等于确保我们的输入数组至少具有一个值。 To help prevent against SQL injection attacks, first generate a ? 为了防止SQL注入攻击,请首先生成一个? for each input item to create a parameterized query. 为每个输入项创建一个参数化查询。 Here I assume that the array containing your ids is called $ids : 在这里,我假设包含您的id的数组称为$ids

$in = join(',', array_fill(0, count($ids), '?'));$select = <<<SQLSELECT *FROM galleriesWHERE id IN ($in);
SQL;

Given an input array of three items $select will look like: 给定一个包含三个项目的输入数组, $select看起来像:

SELECT *
FROM galleries
WHERE id IN (?, ?, ?)

Again note that there is a ? 再次注意,有一个? for each item in the input array. 输入数组中的每个项目。 Then we'll use PDO or MySQLi to prepare and execute the query as noted above. 然后,我们将使用PDO或MySQLi来准备和执行上述查询。

Using the IN() operator with strings 对字符串使用IN()运算符

It is easy to change between strings and integers because of the bound parameters. 由于绑定了参数,因此很容易在字符串和整数之间进行更改。 For PDO there is no change required; 对于PDO,无需更改; for MySQLi change str_repeat('i', to str_repeat('s', if you need to check strings. 对于MySQLi str_repeat('s',如果需要检查字符串str_repeat('s',请将str_repeat('i',更改为str_repeat('s',

[1]: I've omitted some error checking for brevity. [1]:为简洁起见,我省略了一些错误检查。 You need to check for the usual errors for each database method (or set your DB driver to throw exceptions). 您需要检查每种数据库方法的常见错误(或将数据库驱动程序设置为引发异常)。

[2]: Requires PHP 5.6 or higher. [2]:需要PHP 5.6或更高版本。 Again I've omitted some error checking for brevity. 同样,为了简洁起见,我省略了一些错误检查。


#3楼

Basic methods to prevent SQL injection are: 防止SQL注入的基本方法是:

  • Use prepared statements and parameterized queries 使用准备好的语句和参数化查询
  • Escaping the special characters in your unsafe variable 转义不安全变量中的特殊字符

Using prepared statements and parameterized queries query is considered the better practice, but if you choose the escaping characters method then you can try my example below. 使用准备好的语句和参数化查询是更好的做法,但是,如果选择转义字符方法,则可以尝试下面的示例。

You can generate the queries by using array_map to add a single quote to each of elements in the $galleries : 您可以使用array_map$galleries中的每个元素添加一个单引号来生成查询:

$galleries = array(1,2,5);$galleries_str = implode(', ',array_map(function(&$item){return "'" .mysql_real_escape_string($item) . "'";}, $galleries));$sql = "SELECT * FROM gallery WHERE id IN (" . $galleries_str . ");";

The generated $sql var will be: 生成的$ sql var将为:

SELECT * FROM gallery WHERE id IN ('1', '2', '5');

Note: mysql_real_escape_string , as described in its documentation here , was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. 注意: mysql_real_escape_string 如其文档所述,在PHP 5.5.0中已弃用,在PHP 7.0.0中已将其删除。 Instead, the MySQLi or PDO_MySQL extension should be used. 相反,应使用MySQLi或PDO_MySQL扩展。 See also MySQL: choosing an API guide and related FAQ for more information. 另请参见MySQL:选择API指南和相关的FAQ,以获取更多信息。 Alternatives to this function include: 此功能的替代方法包括:

  • mysqli_real_escape_string() mysqli_real_escape_string()

  • PDO::quote() PDO :: quote()


#4楼

As Flavius Stef's answer , you can use intval() to make sure all id are int values: 作为Flavius Stef的答案 ,您可以使用intval()来确保所有id都是int值:

$ids = join(',', array_map('intval', $galleries));
$sql = "SELECT * FROM galleries WHERE id IN ($ids)";

#5楼

Safer. 更安全

$galleries = array(1,2,5);
array_walk($galleries , 'intval');
$ids = implode(',', $galleries);
$sql = "SELECT * FROM galleries WHERE id IN ($ids)";

#6楼

Besides using the IN query, you have two options to do so as in an IN query there is a risk of an SQL injection vulnerability. 除了使用IN查询外,您还有两种选择,因为在IN查询中存在SQL注入漏洞的风险。 You can use looping to get the exact data you want or you can use the query with OR case 您可以使用循环获取所需的确切数据,也可以将查询与OR案例一起使用

1. SELECT *FROM galleries WHERE id=1 or id=2 or id=5;2. $ids = array(1, 2, 5);foreach ($ids as $id) {$data[] = SELECT *FROM galleries WHERE id= $id;}

使用WHERE子句将数组传递给查询相关推荐

  1. 传递数组_Fortran:派生数组与数组传递进子程序耗费时间比较

    在优化程序的过程中发现其中存在大量的派生类型变量(type),同时发现Fortran子程序可以接受type类型数组中元素,即将type类型中元素当作独立的数组传递.传递过程如下所示: ... type ...

  2. Java层与Jni层的数组传递(转)

    源:Java层与Jni层的数组传递 Android开发中,经常会在Java代码与Jni层之间传递数组(byte[]),一个典型的应用是Java层把需要发送给客户端的数据流传递到Jni层,由Jni层的S ...

  3. C语言 数组传递与值传递讲解

    在普通变量或下标变量作函数参数时,形参变量和实参变量是由编译系统分配的两个不同的内存单元.在函数调用时发生的值传送是把实参变量的值赋予形参变量.在用数组名作函数参数时,不是进行值的传送,即不是把实参数 ...

  4. ajax传数组到php页面上,将ajax中的元素值和数组传递到PHP页面

    我正在建立一个像这样的数组: $('.el').each(function(e) { arr.push({ date: $(this).data('date'), roomid : $(this).d ...

  5. java层 android_Android开发实践:Java层与Jni层的数组传递

    Android开发中,经常会在Java代码与Jni层之间传递数组(byte[]),一个典型的应用是Java层把需要发送给客户端的数据流传递到Jni层,由Jni层的Socket代码发送出去,当然,Jni ...

  6. 今晚被两个bug 困扰---第一个,小程序数组传递到PHP后台变成了字符串,导致解析失败

    1.今晚被两个bug 困扰-第一个,小程序数组传递到PHP后台变成了字符串,导致解析失败 2.解决方法 小程序部分: var that = this; console.log(this.data.co ...

  7. fortran subroutine_Fortran:派生数组与数组传递进子程序耗费时间比较

    在优化程序的过程中发现其中存在大量的派生类型变量(type),同时发现Fortran子程序可以接受type类型数组中元素,即将type类型中元素当作独立的数组传递.传递过程如下所示: ... 为了测试 ...

  8. c中将数组传递给子函数_在C ++中将对象传递给Non-Member函数

    c中将数组传递给子函数 Here, we have to define a Non-Member Function, in which we have to pass an Object to the ...

  9. js二维数组传递java,ActiveX获取JavaScript传递的二维数组

    此文参考了http://blog.csdn.net/playstudy/article/details/8259737,在此基础上做了改进 // WebDlg.idl : WebDlg 的 IDL 源 ...

最新文章

  1. sklearn 聚类 实例
  2. 翻译:SQL Server中的索引内部结构:到SQL Server索引级别10的阶梯。
  3. 《分布式系统》教学大纲
  4. python中赋值语句_python中赋值语句和增强赋值语句的区别
  5. Discuz! 全局变量 $_G
  6. Mr.J--验证码登陆模块
  7. [C++] Pure Virtual Function and Abstract Class
  8. 设计灵感|排版死板?可能是你的角度不对!
  9. flex4.5的DataGrid
  10. python获取sessionid_Python Flask:跟踪用户会话?如何获取会话Cookie ID?
  11. opecv-putText
  12. PcShare 2005 源代码
  13. 运维(19) 制作U盘启动盘安装CentOS7
  14. 技巧:彻底删除电脑弹窗广告,还你一个干净的桌面!
  15. paddleHub(一)使用预训练模型推理
  16. 让座席管理工作听得见也看得着
  17. Android Service之设备存储空间监控
  18. [基础]-beautifulsoup模块使用详解
  19. linux 机器开机自动运行命令的方法
  20. Python打包exe程序(pyinstaller)以及打包文件太大的解决方法

热门文章

  1. How to protect video content (Flash Media Server)
  2. Android启动模式详解
  3. window7/10 安装Tomcat
  4. 算法---------两个数的交集
  5. Android CountDownTimer倒计时器的使用
  6. 第八周项目二-用对象数组操作长方柱类
  7. 第六周项目四-静态成员应用
  8. Activity应用场景解析
  9. 如何在Storyboard中使用Scroll view
  10. 树莓派私有云(OwnCloud)搭建(三) OwnCloud安装