循环内 PDO 语句的绑定参数 [英] Binding params for PDO statement inside a loop

查看:23
本文介绍了循环内 PDO 语句的绑定参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在循环内绑定 SQL 查询的参数:

I'm trying to bind parametres for SQL query inside a loop:

$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.

The code above inserts in database in all 3 fields 2010-whatever.

这个很好用:

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

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

So, my question is why the code in the foreach-loop fails and inserts wrong data in the fields?

推荐答案

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

The problem is that bindParam requires a reference. It binds the variable to the statement, not the value. Since the variable in a foreach loop is unset at the end of each iteration, you can't use the code in the question.

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

You can do the following, using a reference in the 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:

Or you could do this, using bindValue:

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

这篇关于循环内 PDO 语句的绑定参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆