Search code examples
javascriptmysqlsqlnode.jsmysqljs

MySQL INSERT SET with PASSWORD()


req.body = {
  username: 1,
  password: 1
}

conn.query('INSERT INTO user SET username = ?, password = PASSWORD(?)',
  [req.body.username, req.body.password])

When using MySQL for Nodejs, we can do the above to insert an user.

However, the following is much cleaner (allows more fields to be set by adding to req.body without altering the code):

conn.query('INSERT INTO user SET ?', req.body)

But how do we solve the problem of needing to call PASSWORD() on the req.body.password field?


Solution

  • No, You can not use a MySQl function like this inside a JavaScript code.

    The first approach which you are following is the only way which you have to follow.

    req.body = {
      username: 1,
      password: 1
    }
    
    conn.query('INSERT INTO user SET username = ?, password = PASSWORD(?)',
      [req.body.username, req.body.password])