gpt4 book ai didi

PHP PDO : Binding value in one foreach loop regarding insert into on duplicate key update

转载 作者:行者123 更新时间:2023-11-29 12:45:35 27 4
gpt4 key购买 nike

我使用两个 foreach 循环将值绑定(bind)到位置参数,一个用于 INSERT INTO,另一个用于 DUPLICATE KEY UPDATE。我试图将其减少到只有一个循环。但 array_merge 不起作用。有人能告诉我如何仅使用一个循环来完成它吗?

这是一个例子:

  $facts = array("age","race");

$ifield = "";
$ufield="";
$comma = "";
foreach($facts as $f)
{
$$f = (isset($_POST["$f"])?$_POST["$f"]:"");
if ($$f)
{
$ifield .= $comma.$f;
$ufield .= "{$comma}{$f} = ?";
$comma = ",";
}
}

$i = explode(',',$ifield);

$in = str_repeat('?,', count($i) - 1) . '?';

$sql .= "INSERT INTO `users` (user_id,model_no,{$ifield}) VALUES(?,?,$in)";

$sql .= " ON DUPLICATE KEY UPDATE $ufield";

$users = $dbh->prepare($sql);

$user_id = $_SESSION['user_id'];
$model_no = $_POST["model_no"];

$users->bindValue(1,$user_id);
$users->bindValue(2,$model_no);

/****************************************************************/
$i = 3;

foreach($facts as $f)
{
global $$f;

if ($$f)
{
$users->bindValue($i++, $$f);

}
}

foreach($facts as $f)
{
global $$f;

if ($$f)
{
$users->bindValue($i++, $$f);

}
}

$users->execute();

最佳答案

您不需要在 ON DUPLICATE KEY 子句中使用绑定(bind)参数。使用:

$ufield = "$comma $f = VALUES($f)";

ON DUPLICATE KEY 子句中使用 VALUES(columndname) 使其使用本应插入到该列中的值。请参阅documentation

关于PHP PDO : Binding value in one foreach loop regarding insert into on duplicate key update,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25494917/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com