我正在为我的用户创建一个多步骤表单。他们将被允许更新任何或所有字段。因此,我需要发送这些值,检查它们是否已设置,如果已设置,则运行 UPDATE
。这是我目前所拥有的:
public function updateUser($firstName, $lastName, $streetAddress, $city, $state, $zip, $emailAddress, $industry, $password, $public = 1,
$phone1, $phone2, $website,){
$updates = array(
'firstName' => $firstName,
'lastName' => $lastName,
'streetAddress' => $streetAddress,
'city' => $city,
'state' => $state,
'zip' => $zip,
'emailAddress' => $emailAddress,
'industry' => $industry,
'password' => $password,
'public' => $public,
'phone1' => $phone1,
'phone2' => $phone2,
'website' => $website,
);
这是我的 PDO(好吧,开始尝试)
$sth = $this->dbh->prepare("UPDATE user SET firstName = "); //<---Stuck here
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
return $result;
基本上,我如何创建 UPDATE
语句,以便它只更新数组中不是 NULL
的项目?
我想像这样运行一个 foreach
循环:
foreach($updates as $key => $value) {
if($value == NULL) {
unset($updates[$key]);
}
}
但是如果我不确定这些值,我该如何编写 prepare
语句?
如果我的做法完全错误,请指出正确的方向。谢谢。
最佳答案
首先,使用array_filter
删除所有 NULL 值:
$updates = array_filter($updates, function ($value) {
return null !== $value;
});
其次,绑定(bind)参数,让你活得更轻松:
$query = 'UPDATE table SET';
$values = array();
foreach ($updates as $name => $value) {
$query .= ' '.$name.' = :'.$name.','; // the :$name part is the placeholder, e.g. :zip
$values[':'.$name] = $value; // save the placeholder
}
$query = substr($query, 0, -1).';'; // remove last , and add a ;
$sth = $this->dbh->prepare($query);
$sth->execute($values); // bind placeholder array to the query and execute everything
// ... do something nice :)
关于php - 使用 PDO 更新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15304656/