循环内 PDO 语句的绑定参数不起作用
Binding params for PDO statement inside a loop doesn't work
我想使用 bindParam
将数据插入我的数据库。
这是我的代码的一个简短版本:
$reindex['f_name'] = 'Tom';
$reindex['l_name'] = 'Riddle';
$reindex['date'] = '2020-12-12';
$sql = "INSERT INTO tbl_user (f_name, l_name, date) VALUES (:f_name, :l_name, :date)";
$stmt = $pdo->prepare($sql);
foreach ($reindex as $key => $value) {
echo $key . '<br>'; // look at output
echo $value . '<br><br>';
$stmt->bindParam($key, $value);
}
$stmt->execute();
回显输出:
f_name
Tom
l_name
Riddle
我没有收到任何错误消息。我这样设置错误报告:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
这可行,但我必须单独定义每个绑定:
$stmt->execute([
'f_name' => $reindex['f_name'],
'l_name' => $reindex['l_name'],
'date' => $reindex['date']
]);
如果您从 PDO 手册中应用它
PDOStatement::bindParam
Binds a PHP variable to a corresponding named or question mark placeholder in the SQL statement that was used to prepare the statement. Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.
你会明白在你的循环中你使用了同一个变量 X 次。每次循环都覆盖它。
因此,当实际绑定完成时,在您 ->execute()
您准备好的查询时,您只有一个值,这些变量中循环中的最后一个值
我想使用 bindParam
将数据插入我的数据库。
这是我的代码的一个简短版本:
$reindex['f_name'] = 'Tom';
$reindex['l_name'] = 'Riddle';
$reindex['date'] = '2020-12-12';
$sql = "INSERT INTO tbl_user (f_name, l_name, date) VALUES (:f_name, :l_name, :date)";
$stmt = $pdo->prepare($sql);
foreach ($reindex as $key => $value) {
echo $key . '<br>'; // look at output
echo $value . '<br><br>';
$stmt->bindParam($key, $value);
}
$stmt->execute();
回显输出:
f_name
Tom
l_name
Riddle
我没有收到任何错误消息。我这样设置错误报告:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
这可行,但我必须单独定义每个绑定:
$stmt->execute([
'f_name' => $reindex['f_name'],
'l_name' => $reindex['l_name'],
'date' => $reindex['date']
]);
如果您从 PDO 手册中应用它
PDOStatement::bindParam
Binds a PHP variable to a corresponding named or question mark placeholder in the SQL statement that was used to prepare the statement. Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.
你会明白在你的循环中你使用了同一个变量 X 次。每次循环都覆盖它。
因此,当实际绑定完成时,在您 ->execute()
您准备好的查询时,您只有一个值,这些变量中循环中的最后一个值