php – 使用PDO更新数组

前端之家收集整理的这篇文章主要介绍了php – 使用PDO更新数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在为我的用户创建一个多步骤表单.他们将被允许更新任何或所有字段.所以,我需要发送值,检查它们是否已设置,如果是,则运行UPDATE.这是我到目前为止:
  1. public function updateUser($firstName,$lastName,$streetAddress,$city,$state,$zip,$emailAddress,$industry,$password,$public = 1,$phone1,$phone2,$website,){
  2.  
  3. $updates = array(
  4. '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(嗯,开始尝试)

  1. $sth = $this->dbh->prepare("UPDATE user SET firstName = "); //<---Stuck here
  2. $sth->execute();
  3. $result = $sth->fetchAll(PDO::FETCH_ASSOC);
  4. return $result;

基本上,我如何创建UPDATE语句,以便它只更新数组中非NULL的项?

我想过运行这样的foreach循环:

  1. foreach($updates as $key => $value) {
  2. if($value == NULL) {
  3. unset($updates[$key]);
  4. }
  5. }

但如果我不确定这些值,我该如何编写准备语句?

如果我完全错了,请指出我正确的方向.谢谢.

首先,使用 array_filter删除所有NULL值:
  1. $updates = array_filter($updates,function ($value) {
  2. return null !== $value;
  3. });

其次,绑定参数,使您的生活更轻松:

  1. $query = 'UPDATE table SET';
  2. $values = array();
  3.  
  4. foreach ($updates as $name => $value) {
  5. $query .= ' '.$name.' = :'.$name.','; // the :$name part is the placeholder,e.g. :zip
  6. $values[':'.$name] = $value; // save the placeholder
  7. }
  8.  
  9. $query = substr($query,-1).';'; // remove last,and add a ;
  10.  
  11. $sth = $this->dbh->prepare($query);
  12.  
  13. $sth->execute($values); // bind placeholder array to the query and execute everything
  14.  
  15. // ... do something nice :)

猜你在找的PHP相关文章