Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/234.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 循环内PDO语句的绑定参数_Php_Foreach_Pdo_Prepared Statement - Fatal编程技术网

Php 循环内PDO语句的绑定参数

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

我正在尝试将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>
}

因此,我的问题是为什么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
}