Connection issue while trying run my mysql query via nodejs - mysql

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

Related

MySQL query for filtering

I want to write a query in MySQL for filtering. For example, if there is a column id in table table1 where the filter values for id come in a POST request body, saved in variable A. I want to extract the matching rows if A is not empty and return all rows otherwise. I am not sure about using IN with WHERE.
SELECT * FROM table1 WHERE id IN (A)
One option is that I return all rows from the database and use JavaScript filters, but I don't want to return all rows and expose the entire table to user.
NOTE: A can be a single value, a tuple or an array.
If you use javascript, use A.join(), and sanitize your POST.
var your_post = [1, 2, 3];
var A = your_post.join();
if (A == '') {
var sql = 'SELECT * FROM table1';
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
} else {
var sql = 'SELECT * FROM table1 WHERE id IN (?)';
con.query(sql, [A], function (err, result) {
if (err) throw err;
console.log(result);
});
}

NodeJS MySQL Update If Null

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

Mysql Error: trying to find columns in database

Im trying to insert user data into my mysql database but Im getting this error " sql: 'SELECT * FROM users WHERE undefined = ?' "
Here is my code :
find: function(user = null, callback) {
//if the user variable is defined
if(user) {
var field = Number.isInteger(user) ? 'id' : 'email';
}
// prepare the sql query
let sql = `SELECT * FROM users WHERE ${field} = ?`;
pool.query(sql, user, function(err, result){
if(err) throw err;
if(result.length){
callback(result[0]);
} else {
callback(null);
}
});
},

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

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