我一直在尝试修复以下 PDO 代码上的无效参数号
,但没有成功。我已将范围缩小到 $tid
中生成动态字段和参数的两个 foreach 循环,因为代码在注释掉与 $tid
相关的所有部分时有效。但是,从输出的外观来看,我仍然无法弄清楚循环出了什么问题。谁能看出问题出在哪里吗?
PDO代码:
try
{
$comma = "";
$tno = "";
$c = "1";
foreach($tid as $t)
{
$tno .= "{$comma}tno_{$c}";
$tno_sql .= "{$comma}(SELECT tno from `model` WHERE model_no = :model_no{$c})";
$tno_update .= "{$comma}tno_{$c} = :model_no1{$c}";
$c++;
$comma = ",";
}
$dbh = new PDO("mysql:host=$hostname;dbname=$databasename", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "
INSERT INTO `aid` (user_id,$tno,content,title,budget_min,budget_max,style)
VALUES (
(SELECT id from `users` WHERE user_id = :user_id1),
$tno_sql,:content1,:title1,:budget_min1,:budget_max1,:style1)
ON DUPLICATE KEY UPDATE
$tno_update,content = :content2, title = :title2,budget_min = :budget_min2,
budget_max = :budget_max2,style = :style2
";
$users = $dbh->prepare($sql);
$users->bindValue(':user_id1',$_SESSION["user_id"]);
$users->bindValue(':content1', $content);
$users->bindValue(':content2', $content);
$users->bindValue(':style1', $style);
$users->bindValue(':style2', $style);
$users->bindValue(':budget_min1', $budget_min);
$users->bindValue(':budget_min2', $budget_min);
$users->bindValue(':budget_max1',$budget_max);
$users->bindValue(':budget_max2', $budget_max);
$users->bindValue(':title1', $title);
$users->bindValue(':title2', $title);
$i = 1;
foreach ($tid as $t) {
$users->bindValue(':model_no{$i}', $t);
$users->bindValue(':model_no1{$i}', $t);
print "':model_no{$i}',";
print "':model_no1{$i}',";
$i++;
}
$users->execute();
$dbh = null;
}
最佳答案
改变
$users->bindValue(':model_no{$i}', $t);
$users->bindValue(':model_no1{$i}', $t);
至
$users->bindValue(":model_no$i", $t);
$users->bindValue(":model_no1$i", $t);
字符串插值仅在值位于双引号内时发生。
关于php - 无法修复 PDO 建立动态 sql 时参数编号无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25466512/