How to update multiple columns in mysql using nodejs - mysql

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.

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) {

👨‍🏫 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 🙏.

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

If you have multiple columns update, and need to take the values from the Object,
you can do the following-
let data = {
"table": {
"update_table":"dlrecustomer"
},
"result": {
"pro":"blre",
"pro_id":"BFCA",
"MOBILE":"9506443333",
},
"keys": {
"CUSTOMER":"27799144",
"APPLICATION":"5454642463"
},
}
let update_set = Object.keys(data.result).map(value=>{
return ` ${value} = "${data.result[value]}"`;
});
let update_query = `UPDATE ${data.table.update_table} SET ${update_set.join(" ,")} WHERE CUST_ID = "${data.keys.CUSTOMER}" AND APPL_ID = "${data.keys.APPLICATION}"`;

Related

update a object second value as a object with JSON_SET in mysql apostrof problem

I hava a longtext type column in mysql and it is default value is like that :
{"aaaaa": [], "bbbbb": []}
when I want to update that column with :
const IamCreator = 1;
const myValue= [1,22,66,77]; //object
const query = `UPDATE 8users SET content = JSON_SET(content, '$.aaaaa', '?') WHERE id = ?`;
connection.query(query,[myValue,IamCreator],function (err, result, fields) {
console.log(err)
})
it give syntex problemand update value like that ;
{"aaaaa": "[1,22,66,77]", "bbbbb": []}
how can I solve that appostrof prolem?
I tried :
content = JSON_SET(content, '$.aaaaa', ?)
content = JSON_SET(content,'$.aaaaa', [?])
const query = `UPDATE table SET json_column = JSON_SET(json_column, '$.mykanban', ?) WHERE id = ?`; connection.query(query, [JSON.stringify(myValue), IamCreator]);
ı took syntex error all the time

My Sql query return an empty array with req.params.id in nodejs

I have i Mysql query with nodejs like this :
application.get('/Modification/:idt',function(req,res){
connection.query("SELECT * FROM memos WHERE idMemo = 'req.params.idt'",function (error, rows){
if (error) {
console.log("error ocurred",error);
}
else {
console.log(req.params.idt);
console.log(rows);
var no = rows;
res.render('memosModif.ejs', {no});
}
});
});
and my query return an empty array even if req.params.idt return an int value like 1 or 2 ... , but when i replace req.params.id with a int like 1 or 2 ... the query returns the right result
i dont understand why and how to fix that .
You are comparing the idMemo column to the string literal 'req.params.idt'. Instead, you should bind the value from this variable:
connection.query("SELECT * FROM memos WHERE idMemo = ?", req.params.idt, function (error, rows) {

Query in Mysql and Node.js

I have this Mysql query that is working fine. However, I need to add 2 more conditions and I'm not sure how to do this.
//index.js
module.exports = {
getHomePage: (req, res) => {
let query ='SELECT Tbl_Email_mensagens.codigo AS Codigo, Tbl_Email_mensagens.mensagem AS Mensagem,Tbl_Email_mensagens.celular AS Celular, cm_custmaster.fullname AS NomeCompleto FROM Tbl_Email_mensagens LEFT JOIN cm_custmaster ON Tbl_Email_mensagens.celular = cm_custmaster.mobile';
// execute query
db.query(query, (err, result) => {
if (err) {
res.redirect('/');
}
res.render('index.ejs', {
title: ""
,players: result
});
});
},
};
I then need to add these 2 conditions:
Where group = '7' and send = '0'
Very thanks!
SELECT Tbl_Email_mensagens.codigo AS Codigo,
Tbl_Email_mensagens.mensagem AS Mensagem,
Tbl_Email_mensagens.celular AS Celular,
cm_custmaster.fullname AS NomeCompleto
FROM Tbl_Email_mensagens
LEFT JOIN cm_custmaster ON Tbl_Email_mensagens.celular = cm_custmaster.mobile
WHERE Tbl_Email_mensagens.`group` = 7
AND Tbl_Email_mensagens.send = 0
Pay attention - the word group is reserved one, so it MUST be wrapped into backticks. But it is more safe to rename it, to some group_number, for example.
Whereas the quotes over the values are excess (you may store them if according field has any string datatype).

MYSQL UPDATE TEXT field not working

I'm trying to update a TEXT field in a MYSQL table. I can't get the UPDATE query to work, even though the original INSERT attempt works fine when the user doesn't exist.
The purpose of the function is to INSERT new row if the user doesn't exist yet, and to UPDATE the textColumn (that always contains a JSON) if the user already exists in the table.
My code:
let first = 'jake';
let last = 'mcdonald';
let first_json = JSON.stringify({a:7, b:7});
let second_json = JSON.stringify({a:'updated'});
const row = {
name: first,
last_name: last,
textColumn: first_json,
}
db.query(`SELECT * FROM tableName
WHERE name="${first}"
AND last_name="${last}"`, (err, result) => {
if (err) console.log(err);
if (result.length < 1) {
db.query(`INSERT INTO tableName SET ?`, row, (err, result) => {
console.log('NEW ROW CREATED: ', result);
})
} else if (result.length > 0) {
console.log('ROW EXISTS');
db.query(`UPDATE tableName
SET textColumn=${second_json}
WHERE name="${first}"
AND last_name="${last}"`, (err, result) => {
console.log('UPDATED: ', result);
}
)
}
}
)
the else if section is what is giving me issues: I reach the inside console.log('ROW EXISTS') but the Update query logs "undefined".
The same UPDATE query works if I try to UPDATE tableName SET name="someNewName" WHERE last_name="original_last_name", but nothing happens when I try to UPDATE the textColumn.

Connection issue while trying run my mysql query via nodejs

I have a query and I am trying to run the query. The issue i think is that i have added a condition where an item from a column from the database must equal to the computer name of the user.
Hence, I created a variable called computerName that simply retrieves the host name of the computer via NodeJs.
var os = require("os");
var computerName = os.hostname(); // Detect the computer name associated with the tablet
Below is the query
connection.query("SELECT box_id, longestDimension from box where longestDimension != '' AND LOWER(box_id) = LOWER(computerName)", function(err, rows, fields) {
computerName seems to be the problem because when the query is run with a generic name such as box45 it works.
I am getting connection error. I guess the better question is how do I include a defined variable into the query
It looks like you're trying to insert computerName directly into your SQL statement. At minimum, you'd need to write something like
connection.query("SELECT box_id, longestDimension from box where longestDimension != '' AND LOWER(box_id) = LOWER('" + computerName + "')", function(err, rows, fields) {
But you should be escaping the value of computerName. You don't know what value it might contain.
connection.query("SELECT box_id, longestDimension from box where longestDimension != '' AND LOWER(box_id) = LOWER('" + connection.escape(computerName) + "')", function(err, rows, fields) {
But a better way to do it is with ? substitution:
connection.query("SELECT box_id, longestDimension from box where longestDimension != '' AND LOWER(box_id) = LOWER(?)", computerName, function(err, rows, fields) {
Also, if the collation of the box_id column is case insensitive, which is usually the default, then you can skip the lowercasing the values.
I'd write it like this, for readability
let sql = "SELECT box_id, longestDimension FROM box WHERE longestDimension != '' AND box_id = ?";
connection.query(sql, computerName, function(err, rows, fields) {
Or if your node version supports template literals
let sql = `SELECT box_id, longestDimension
FROM box
WHERE longestDimension != ''
AND box_id = ?`;
connection.query(sql, computerName, function(err, rows, fields) {
If you have multiple variables there's two ways to do it: with an object, or with an array.
Object method:
let payload = {
box_id: "Johannesburg",
longestDimension: 12.4
};
let sql = 'INSERT INTO box SET ?';
connection.query(sql, payload, function(err, rows, fields) {
});
Array method:
let computerName = "Johannesburg";
let longestDimension = 12.4;
let sql = 'INSERT INTO box SET box_id = ?, longestDimension = ?';
// alternative, equivalent SQL statement:
// let sql = 'INSERT INTO box (box_id, longestDimension) VALUES (?, ?)';
connection.query(sql, [ computerName, longestDimension ], function(err, rows, fields) {
});
You can even combine them
let payload = {
box_id: "Johannesburg",
longestDimension: 12.4
};
let boxName = "Box A";
let sql = 'UPDATE box SET ? WHERE box_name = ?';
connection.query(sql, [ payload, boxName ], function(err, rows, fields) {
});
In this last example, the payload object is substituted for the first ? and the boxName variable is substituted for the second ?.