SQL:如果值为空,则不覆盖tablecell

时间:2018-03-08 09:00:10

标签: php mysql sql-update

我想知道是否可以仅使用空值来更新SQL行。

用户想要更新其帐户数据,并将电子邮件字段留在html表单空白处。生成的PHP数组应该更新到数据库,但只有空白的值:

import React, { Component } from 'react';

export default class checkBox extends Component {

    constructor(){
        super();

        this.state = {
            checkboxState: false
        };
        this.toggle = this.toggle.bind(this);
    }
    toggle(e){
        console.log('toggle was triggered');
    }

    render(){

        let miniBox = this.props.plz_zwischen.map(function(a, index){
            return <li key={index} data={a}> <label> {a} </label> <input type="checkbox"  onClick={(e) => this.toggle()} /></li>;
        });

        return(
            <div>
                <ul id="rowlist">
                    {miniBox}
                </ul>
            </div>
        );
    }
}

SQL-更新:

Array
(
    [id] => 9505399
    [first_name] => Max
    [last_name] => Mustermann
    [email] => 
    [location] => cologne
    [country] => germany
)

问题:如果用户之前已设置过他的电子邮件,则此SQL更新将使用空值覆盖现有条目(电子邮件)。我需要防止单元格被空值覆盖。

2 个答案:

答案 0 :(得分:1)

您可以使用array_filter()从数组中删除空值。然后你可以像这样动态地构建你的查询:

$arr = array_filter($arr); // remove empty values
$args = [];
$qryargs = [];
foreach ($arr as $key => $val) {
    $args[':'.$key] = $val ; // populate query arguments 
    if ($key == 'id') continue ; // remove id from SET statement
    $qryargs[] = $key . ' = :' . $key;
}
// build query string
$sql = "UPDATE  observation SET " . implode(', ', $qryargs). " WHERE id = :id";

echo $sql ;
print_r($args);

输出:

UPDATE  observation SET first_name = :first_name, last_name = :last_name, 
        location = :location, country = :country WHERE id = :id

Array
(
    [:id] => 9505399
    [:first_name] => Max
    [:last_name] => Mustermann
    [:location] => cologne
    [:country] => germany
)

答案 1 :(得分:0)

如果您想要纯SQL解决方案,可以使用CASE语句:

UPDATE observation
SET 
first_name = CASE
   WHEN first_name IS NULL OR first_name = '' THEN :first_name
   WHEN first_name <> 0 THEN first_name 
END,
last_name = ...
WHERE id = :id;

另外,我相信,您并不是每次都想更新用户的ID。