使用PDO更新数组

Pau*_*ert 7 php pdo

我正在为我的用户创建一个多步骤表单.他们将被允许更新任何或所有字段.所以,我需要发送值,检查它们是否已设置,如果是,请运行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,

);
Run Code Online (Sandbox Code Playgroud)

这是我的PDO(嗯,开始尝试)

    $sth = $this->dbh->prepare("UPDATE user SET firstName = "); //<---Stuck here
    $sth->execute();
    $result = $sth->fetchAll(PDO::FETCH_ASSOC);
    return $result; 
Run Code Online (Sandbox Code Playgroud)

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

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

    foreach($updates as $key => $value) {
        if($value == NULL) {
            unset($updates[$key]);
        }
    }
Run Code Online (Sandbox Code Playgroud)

prepare如果我不确定这些值,我该怎么写这个陈述呢?

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

Wou*_*r J 5

首先,用于array_filter删除所有NULL值:

$updates = array_filter($updates, function ($value) {
    return null !== $value;
});
Run Code Online (Sandbox Code Playgroud)

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

$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 :)
Run Code Online (Sandbox Code Playgroud)