我正在尝试在循环内绑定 SQL 查询的参数:
$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
需要参考。它将变量绑定到语句,而不是值。由于a中的变量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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)