Php 循环内PDO语句的绑定参数
我正在尝试将SQL查询的参数绑定到循环中:Php 循环内PDO语句的绑定参数,php,foreach,pdo,prepared-statement,Php,Foreach,Pdo,Prepared Statement,我正在尝试将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 = a
$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>
}
因此,我的问题是为什么foreach循环中的代码会失败,并在字段中插入错误的数据?问题是
bindParam
需要引用。它将变量绑定到语句,而不是值。由于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
}
你好,我遇到了一个类似的问题。你能帮我一下吗?问题是——哪一个更好?bindValue或bindParam。@IdanMagled在这里我认为
bindValue
更直观bindParam
在某些情况下具有优势。&
在&$value
中做什么?@Taurus它将$value
作为数组元素的引用,而不是复制其值。
foreach ($reindex as $key => $value) {
$stmt->bindValue($key, $value); // bind the value to the statement
}