問題描述
我正在嘗試在循環內綁定 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 語句的綁定參數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!