gpt4 book ai didi

php - 循环内 PDO 语句的绑定(bind)参数

转载 作者:IT王子 更新时间:2023-10-29 01:24:25 24 4
gpt4 key购买 nike

我正在尝试在循环内为 SQL 查询绑定(bind)参数:

$db = new PDO('mysql:dbname=test;host=localhost', 'test', '');  
$stmt = $db->prepare('INSERT INTO entries VALUES (NULL, ?, ?, ?, NULL)');

$title = 'some titile';
$post = 'some text';
$date = '2010-whatever';

$reindex = array(1 => $title, $post, $date); // indexed with 1 for bindParam

foreach ($reindex as $key => $value) {
$stmt->bindParam($key, $value);
echo "$key</br>$value</br>"; //will output: 1</br>some titile</br>2</br>some text</br>3</br>2010-whatever</br>
}

上面的代码在所有 3 个字段 2010-whatever 中插入数据库。

这个很好用:

$stmt->bindParam(1, $title);
$stmt->bindParam(2, $post);
$stmt->bindParam(3, $date);

那么,我的问题是为什么 foreach 循环中的代码会失败并在字段中插入错误的数据?

最佳答案

问题是 bindParam 需要引用。它将变量绑定(bind)到语句,而不是值。由于 foreach 循环中的变量在每次迭代结束时未设置,因此您不能使用问题中的代码。

您可以使用 foreach 中的引用执行以下操作:

foreach ($reindex as $key => &$value) {  //pass $value as a reference to the array item
$stmt->bindParam($key, $value); // bind the variable to the statement
}

或者你可以这样做,使用bindValue:

foreach ($reindex as $key => $value) {
$stmt->bindValue($key, $value); // bind the value to the statement
}

关于php - 循环内 PDO 语句的绑定(bind)参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4174524/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com