4

I have a JSON Object and want to UPDATE a mySQL table, without List all of the Keys

with an INSERT I do this like

    var arrayValue = Object.keys(obj).map(function(key) {
      return String("'"+obj[key]+"'");
    });

    var arrayKeys = Object.keys(obj).map(function(key) {
      return String(key);
    });
    var sql = "INSERT INTO `modules` "+ " (" +arrayKeys.join() + ") VALUES ("+arrayValue.join()+");";
    con.query(sql, function (err, result, fields) {
      if (err) throw err;
      return result;
    });

The same i would do with UPDATE

How can i do this?

1
  • Can you update the question with the JSON object and what exactly would be your update query is mysql from that json object. Commented Nov 22, 2019 at 20:05

2 Answers 2

4

does this fill your needs?

const object = {
    id: 1,
    firstName: "John",
    lastName: "Doe"
};

const columns = Object.keys(object);
const values = Object.values(object);

let sql = "INSERT INTO tableName ('" + columns.join("','") +"') VALUES (";

for (let i = 0; i < values.length; i++) {
    sql += "?";
    if (i !== values.length - 1) {
        sql += ",";
    }
}

sql+= ")";

connection.query(sql, values, (error, result, fields) => {
    //do what you must here.
});

For update:

const object = {
    id: 1,
    firstName: "John",
    lastName: "Doe"
};

const columns = Object.keys(object);
const values = Object.values(object);

let sql = "UPDATE tableName SET '" + columns.join("' = ? ,'") +"' = ?";

connection.query(sql, values, (error, result, fields) => {
    //do what you must here.
});

Off course what would you put in the where statement?

I hope this helped.

Sign up to request clarification or add additional context in comments.

Comments

2

here the example

/ Update an existing user
app.put('/users/:id', (request, response) => {
    const id = request.params.id;

    pool.query('UPDATE users SET ? WHERE id = ?', [request.body, id], (error, result) => {
        if (error) throw error;

        response.send('User updated successfully.');
    });
});

that works for me

1 Comment

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.