PHP PDO MySQL IN (?,?,?

空扰寡人 提交于 2020-02-20 05:32:46

问题


I want to write a MySQL statement like:

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

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

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.

Something like:

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

Is that possible?


回答1:


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

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.



来源:https://stackoverflow.com/questions/2814466/php-pdo-mysql-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!