简体   繁体   English

如果 POST['submitted_field'] 不是 Null MariaDB、MySQL,则更新行字段

[英]Update Row Fields if POST['submitted_field'] Is Not Null MariaDB , MySQL

Hi I'm trying to update user information on valid submit in my query it's possible to update multiple columns only if it's relevant $_POST[ ] is not null how i can do that?嗨,我正在尝试在我的查询中更新有效提交的用户信息,只有当相关的 $_POST[] 不是 null 时,才可以更新多个列,我该怎么做? used tool php, MariaDB or mysql I. I tried something like this but it returns syntax error corresponding to MariaDB使用过的工具 php、MariaDB 或 mysql I. 我尝试过类似的操作,但它返回对应于 Z7F97633E208BE7658B1CE 的语法错误

 $query = " UPDATE `users`
            SET name = COALESCE($name, name),
            title = COALESCE($title, title),
            email = COALESCE($email, email),
            gender = COALESCE($gender, gender)
            WHERE `id` = '" . $_SESSION['id'] . "'   LIMIT 1";

You can have a helper for doing that你可以有一个帮手来做这件事

function getUserUpdateQuery(array $data, $userId)
{
    $condition = 'WHERE id = '.$userId;
    $query = 'UPDATE `users` SET ';
    $updates = [];

    foreach ($data as $columnName => $columnValue) {
        if( !is_null($columnValue) )
        {
            $updates[] = sprintf('`%s` = \'%s\'', $columnName, $columnValue);
        }
    }

    $query .= implode(' AND ', $updates).' ';

    $query .= $condition;

    return $query;
}

$query = getUserUpdateQuery(['title' => $title, 'email' => $email], $_SESSION['id']);

// updating codes here

Note: in production environment it is better practice to bind data.注意:在生产环境中,最好是绑定数据。 PDO is a good tool for doing that. PDO 是一个很好的工具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM