4

How to update the multiple columns in MySQL using node.js:

var query = 'UPDATE employee SET profile_name = ? WHERE id = ?';
connection.query(query,[req.name,req.id] function (error, result, rows, fields) {

but I have to update profile_name, phone,email, country, state, address at once.
How can I do that, can anyone suggest.

3
  • In case you see this: Titus posted the best answer, and it should be the accepted one. Commented Jan 29, 2020 at 14:13
  • @ChrisG Do you see the date of the question? I think the answer from today is not relevant for OP Commented Jan 29, 2020 at 15:19
  • @Jens I'm fully aware that this question was posted in 2016, it is however a perfect duplicate of a current question which I wanted to flag as such. To my knowledge SO is supposed to be a repository of useful questions and answers, and updating an older question / answer is not only acceptable but encouraged. Commented Jan 29, 2020 at 18:35

3 Answers 3

12

Simply add all columns in set:

var query = 'UPDATE employee SET profile_name = ?, phone =?, .. WHERE id=?';

connection.query(query,[req.name,req.phone,...,req.id] function (error, result, rows, fields) {
Sign up to request clarification or add additional context in comments.

3 Comments

There's no way to do this dinamically? Something like calling an utility function passing only the column names?
@GiulianaBezerra There is: one can pass an object to SET ?. See here: stackoverflow.com/a/59960177/5734311
@Downvoter: Thanks for downvoting without explanation
8

👨‍🏫 To update your multiple columns in mysql using nodejs, then You can do it like this code below: 👇

const query = 'UPDATE `employee` SET ? WHERE ?';
connection.query(query, [req.body, req.params], function(err, rows) {
  if(err) {
    console.log(err.message);
    // do some stuff here
  } else {
    console.log(rows);
    // do some stuff here
  }
});

💡 Make sure your req.body is not empty and the field in your req.body it's same with the field in your employee table.

If your req.body is undefined or null, then you can add this middleware to your express server:

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

I hope it can help you 🙏.

Comments

1

UPDATE statement syntax :

UPDATE <TableName>
SET <Col1> = <Val1>,
    <Col2> = <Val2>,
    ....
WHERE id = ?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.