Why are these variables being inserted into the wrong part of my node.js sql query?

Tom Davies :

I am trying to run an sql query using Node.js, using a prepared statement, as follows:

sql = "UPDATE users SET ? WHERE user_id = ?"
        con.query(sql, {current_quiz: quizId, user_id: selected[0]},
        function(result, err) {
          if(err) throw err
          console.log(result)
        })

However the result returns an error, because the code is inserting an extra column into the query:

sql: 'UPDATE users SET `current_quiz` = 1, `user_id` = \'1\' WHERE user_id = ?'

What can I do to ensure that selected[0] is used by the user_id= part of the statement, rather than added as an extra column/value pair?

O. Jones :

Use an array, not an object, to give your parameters to a query like that.

const sql =
 'UPDATE users SET current_quiz = ? WHERE user_id = ?'
con.query(sql, [quizId, selected[0]] ...

The query() method takes them in order.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=407782&siteId=1