PHP PDO MySQL IN(?,?,? [英] PHP PDO MySQL IN (?,?,?

查看:59
本文介绍了PHP PDO MySQL IN(?,?,?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个MySQL语句,例如:

I want to write a MySQL statement like:

SELECT * FROM someTable WHERE someId IN (value1, value2, value3, ...)

这里的诀窍是我不知道提前知道IN()中会有多少个值.

The trick here is that I do not know ahead of time how many values there will be in the IN().

很明显,我知道我可以通过字符串操作随时生成查询,但是由于这将循环运行,所以我想知道是否可以使用PDO PreparedStatement进行查询.

Obviously I know I can generate the query on the go with string manipulations, however since this will run in a loop, I was wondering if I could do it with a PDO PreparedStatement.

类似的东西:

$query = $PDO->prepare('SELECT * FROM someTable WHERE someId IN (:idList)');
$query->bindValue(':idList', implode(',', $idArray));

有可能吗?

推荐答案

这不是您尝试的方法.您要传递的每个参数都必须有一个单独的占位符,其他所有内容都会违背参数的目的(将代码与数据分开).

This is not possible the way you try it. You must have a separate placeholder for every parameter you want to pass in, everything else would defy the purpose of parameters (which is separating code from data).

$ids = array(2, 4, 6, 8);

// prepare a string that contains ":id_0,..,:id_n" and include it in the SQL
$plist = ':id_'.implode(',:id_', array_keys($ids));
$sql   = "SELECT * FROM someTable WHERE someId IN ($plist)";
// prepare & execute the actual statement
$parms = array_combine(explode(",", $plist), $ids);
$stmt  = $PDO->prepare($sql);
$rows  = $stmt->execute($parms);

如果在绑定期间允许您将值的数组传递给单个参数,则将有效地允许您更改SQL语句.这将是SQL注入的漏洞-毕竟,没有什么可以保证所有数组值都是无辜的整数.

If you were allowed to pass in an array of values to a single parameter during bind, you would effectively be allowed to alter the SQL statement. This would be a loophole for SQL injection - nothing could guarantee that all array values would be innocent integers, after all.

这篇关于PHP PDO MySQL IN(?,?,?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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