NodeJS MySQL Update If Null - mysql

I'm using MySQL with NodeJS and I'm just pretty new.
I want to UPDATE col value if it's null else UPDATE for another col.
Simply like that: If col1 is null UPDATE else UPDATE col2.
app.post('/api/update', (req, res) => {
const convidn = req.body.conversationid
const currentuser = req.body.current
var sql = "UPDATE messages SET whodeleted='"+currentuser+"' WHERE converid = '" + convidn + "'";
That overwrites column value. I just want to if "whodeleted" is not null UPDATE for "whodeleted2" colum.
db.query(sql, (err, result) => {
if (err) throw err;
console.log("Number of records deleted: " + result.affectedRows);
});
})

You can do something like this
But your code is vulnerable to sql inject please read Preventing SQL injection in Node.js to so how you can avoid it
UPDATE messages
SET
whodeleted = CASE
WHEN whodeleted IS NULL THEN ?
ELSE whodeleted
END,
col2 = CASE
WHEN whodeleted IS NULL THEN col2
ELSE 'test'
END
WHERE
converid = ?

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

Node.js + SQL - is Insert query faster than Select?

I have a problem with SQL in node.js.
I have an array 'data' which contains some data returned from the async function and I want to put it into MySQL database if there's no result with the same data. There are some duplicated objects in array but I want to put just one into database.
Function example:
async function data_name(param){
var data = [];
data.push({
name: param,
sname: 'sname',
url: 'url',
report: 'report'
});
return data;
}
Then I run following code:
var data = await data_name('name');
data.forEach(item=>{
var chk = "SELECT * FROM `?` WHERE `name` = ? AND `sname` = ?;";
con.query(chk, [tablename, item.name, item.sname], function(er,items){
if(er) throw er;
if(items.length < 1){
var insert = "INSERT INTO `?` (name, sname, url, report) VALUES (?,?,?,?)";
con.query(insert, [tablename, item.name, item.sname, item.url, item.report], function(erg,added){
if(erg) throw erg;
console.log('Item added: ' + item.name);
});
}
else{
if(items[0].report != item.report){
var upd = "UPDATE `?` SET report = ? WHERE id = ?";
con.query(upd, [tablename, item.report, items[0].id], function(ere,edited){
if(ere) throw ere;
console.log('Item updated: ' +items[0].name);
});
}
}
//broken code below
var adc = "SELECT * FROM `links` WHERE `link` = ?;";
con.query(adc, item.url, function(erc, results){
//tried also with: results[0] === undefined || results[0] === null
var test = item.url + ' ' + results.length;
console.log(test);
if(results.length < 1){
var add_c = "INSERT INTO `links` (link_name, link_url) VALUES (?,?)";
con.query(add_c, [item.name, item.url], function(era, a_link){
if(era) throw era;
});
}
else{console.log('Record exists');}
});
});
});
The first SQL works great: it inserts all records to database, there are no duplicates and it updates values if it is required.
Second SQL (mentioned by a comment in code that I put before) doesn't work properly if the database is empty. It duplicates records in database (after running it database has 470 records while every record is duplicated about 8 times).
test variable prints for eg:
https://google.com 0
https://google.com 0
https://facebook.com 0
https://facebook.com 0
https://google.com 1
https://facebook.com 0
https://google.com 0
The problem exists only if a database is empty (if I run the code second time, the second SQL doesn't insert records new records and print in console 'Record exists'
Any ideas what can be reason of that?

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 ?.

How to update multiple columns in mysql using nodejs

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}"`;