Search code examples
mysqlnode.jsnode-mysql

How to UPDATE a query with different arguments in MySQL


Environment

Node.js, MySQL (using node-mysql library connect)

At first

I could have one argument 'aaa' or two arguments 'aaa' and 'bbb'.

UPDATE user SET email = 'aaa' WHERE uid = 'xxx';
UPDATE user SET email = 'aaa', password = 'bbb' WHERE uid = 'xxx';

My problem

How could I use one query to overcome above cases? Like below ...

var sql = "UPDATE user SET email = ?, password = ? WHERE uid = ?;"
dbclient.query(sql, [email, password, uid], function (err, results) {
    ...
});
  1. If two arguments were defined, variable sql was :

    sql = "UPDATE user SET email = 'test@mail.com', password = 'abcd' WHERE uid = 1;";
    
  2. If someone argument was undefined, variable sql was :

    sql = "UPDATE user SET email = 'test@mail.com', password = password WHERE uid = 1;";
    

Solution

  • Please read the documentation, especially the section escaping query values. node-mysql supports some neat use of object serialization.

    The following example should be what you want (it uses format, but so does query() internally):

    var mysql = require( 'mysql' );
    
    var credfull = {
            email: "a@exemple.com",
            password: "secret"
        },
        crednopwd = {
            email: "a@exemple.com"
        },
        whereclause = {
            uid: "blabla"
        };
    
    console.log( mysql.format( 'UPDATE user SET ? WHERE ?', [credfull, whereclause]) );
    // UPDATE user SET `email` = 'a@exemple.com', `password` = 'secret' WHERE `uid` = 'blabla'
    
    console.log( mysql.format( 'UPDATE user SET ? WHERE ?', [crednopwd, whereclause]) );
    // UPDATE user SET `email` = 'a@exemple.com' WHERE `uid` = 'blabla'
    

    Hope this helps.