[英]php pdo binding multiple values issue
I have the following code in php to query the database based on an array sent by the client. 我在php中有以下代码,根据客户端发送的数组查询数据库。
$limit = $_POST['limit'];
$userArray = json_decode($_POST['arr'], true);
$queryPlaceholders= implode(',', array_fill(0,count($userArray), '?'));
$stmt = $db->prepare("SELECT * FROM tableA
WHERE tableA.id IN (".$queryPlaceholders.")
LIMIT ?");
foreach($userArray as $k => $val){
$stmt->bindParam(($k+1), $val);
}
$stmt->bindValue(count($userArray) + 1, (int)trim($limit), PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo $result;
This code appears to have an error. 此代码似乎有错误。 If I send an array containing the values 11 & 17, the query seems to only run with the value 17, not both 11 and 17.
如果我发送一个包含值11和17的数组,则查询似乎只运行值17,而不是11和17。
If I print_r($userArray)
I get Array ( [0] => 11 [1] => 17 )
如果我
print_r($userArray)
我得到Array ( [0] => 11 [1] => 17 )
so I know php has the correct array. 所以我知道php有正确的数组。 However, running this query with the code above, and running the query below yields different answers:
但是,使用上面的代码运行此查询,并在下面运行查询会产生不同的答案:
SELECT * FROM tableA
WHERE tableA.id IN (11,17)
LIMIT 10
When running the code above, It appears to infact run this query? 运行上面的代码时,它似乎实际运行此查询?
SELECT * FROM tableA
WHERE tableA.id IN (17)
LIMIT 10
I've also placed statements in the foreach
loop that tells me both elements of the array (11 & 17) are being bound to the $stmt 我还在
foreach
循环中放置了语句,告诉我数组(11和17)的两个元素都绑定到$ stmt
The problem is that you are using bindParam()
: 问题是您使用的是
bindParam()
:
Binds a PHP variable to a corresponding named or question mark placeholder in the SQL statement that was use to prepare the statement.
将PHP变量绑定到用于准备语句的SQL语句中的相应命名或问号占位符。 Unlike
PDOStatement::bindValue()
, the variable is bound as a reference and will only be evaluated at the time thatPDOStatement::execute()
is called.与
PDOStatement::bindValue()
,变量被绑定为引用,并且仅在调用PDOStatement::execute()
时进行计算。
Since $val
is changed on each iteration of the foreach
loop, it ultimately is the same for each placeholder when the query is finally executed. 由于
$val
在foreach
循环的每次迭代中都会更改,因此最终执行查询时,每个占位符最终都是相同的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.