仅更新传递的参数

时间:2015-01-09 14:21:34

标签: php postgresql prepared-statement

有一种方法只更新传递的参数并保持其他参数保持不变?我正在寻找一种方法来避免动态查询。例如我想更改说明字段并保持电子邮件不变:

$MyArray['email']='';
$MyArray['description']='The new description';

$Result = pg_query_params($db,'UPDATE users SET email=$1, description=$2 WHERE id = $3', array($MyArray['email'],$MyArray['description'],$User['id']));

由于 d

2 个答案:

答案 0 :(得分:0)

没有简单方式... SQL没有此功能,但您可以在应用程序逻辑中以简单的方式执行此操作。

  1. 在表单中序列化原始实例数据

    的serialize($ myDataArray)

  2. 发布更新后,将其与序列化数据进行比较

    反序列化($ myDataArray);

    $ diff = array_diff($ original,$ modified);

  3. 这可以让你知道如何做到这一点。

答案 1 :(得分:0)

正如我所做的那样,您可以构建一个小包装来检查更改的值。

在我使用的课程中喜欢这种方法:

    /**
     * Checks for changes between $old and $new.
     * All arrays must be assoc.
     *
     * The keys of $map are the keys of $old and the values of $map are the keys of $new:
     * $map: key => $old[key]
     * $map: val => $new[key]
     *
     * The return is an array with $old keys and $new values.
     *
     * @param array $old
     * @param array $new
     * @param array $map
     */
    public function checkChanges(array $old, array $new, array $map) {
        $toReturn = array();

        foreach ($map as $oldKey=>$newKey) {
            if ($old[$oldKey] != $new[$newKey]) {
                if (is_string($new[$newKey])) {
                    $toReturn[$oldKey] = "'".$new[$newKey]."'";
                } else {
                    $toReturn[$oldKey] = $new[$newKey];
                }
            }
        }

        if (count ($toReturn) == 0 ) {
            return null;
        }

        return $toReturn;
    }

第一个数组包含旧的未更改的值。第二个是新的更改和未更改的值(取决于您或您的用户输入),最后一个将使用该值作为第一个数组的键,同时将该值用作第二个数组的键。

这将是一个仅限PHP的解决方案,它适用于我,因为我只会更新这些值。

注意:它不适用于嵌套数组。如果你有多个阵列,你必须自己解决。