How to insert query in NodeJS with variables - mysql

I have a query, but I am not sure how to allow NodeJS to input it with variables.. how do I achieve this? What is the best way?
var sql = (
"INSERT INTO stats_tmp (
id,
timestamp,
campaign_nm,
calls,
seconds,
answered,
failure,
dnc,
amd,
transfers,
transfer_seconds,
cost
) VALUES ("
+ estarr[0].id + ", "
+ estarr[0].timestamp + ", "
+ estarr[0].name + ", "
+ estarr[1].calls + ", "
+ estarr[1].seconds + ", "
+ estarr[1].answers + ", "
+ estarr[1].failures + ", "
+ estarr[1].dncs + ", "
+ estarr[1].amd + ", "
+ estarr[1].transfers + ", "
+ estarr[1].transfers + ", "
+ estarr[1].transferseconds + ", "
+ estarr[1].cost
+ ")"
);

You want to use prepared statements.
Consider:
var query = connection.query(
'INSERT INTO stats_tmp (
id,
timestamp,
campaign_nm,
calls,
seconds,
answered,
failure,
dnc,
amd,
transfers,
transfer_seconds,
cost
) VALUES (
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?
)',
[
estarr[0].id,
estarr[0].timestamp,
estarr[0].name,
estarr[1].calls,
estarr[1].seconds,
estarr[1].answers,
estarr[1].failures,
estarr[1].dncs,
estarr[1].amd,
estarr[1].transfers,
estarr[1].transfers,
estarr[1].transferseconds,
estarr[1].cost
],
function(err, results) {
...
});

Related

How to remove quotes from json null when concatenating into a string?

I can't get rid of the single quote from around null here:
const obj = {"ItemData": {
"ItemId": 4335549,
"CustID": null,
"dateCreated": "2021-02-01 07:50:51.1670000",
"amount": 10.99
}
}
let x= "'" + obj.ItemData.ItemId + "|''" + obj.ItemData.CustID + "''|" + obj.ItemData.dateCreated +
"|" + obj.ItemData.amount + "'"
regx = /'null'/ig
console.log(x.replaceAll(regx, null))
I get this:
'4335549|'null'|2021-02-01 07:50:51.1670000|10.99'
I want this:
'4335549|null|2021-02-01 07:50:51.1670000|10.99'
Also tried standard replace, same result.
How to remove the quotes from around null?
try this
regx = /''null''/ig
console.log(x.replaceAll(regx, null));
or you can try more generic
let x="";
Object.keys(obj.ItemData).forEach((key) => { x += "|" + obj.ItemData[key] });
x= "'" + x.substring(1) + "'";
You can use the following code to only insert the quotes when the value is not null
let x= "'" + obj.ItemData.ItemId + "|" +
((obj.ItemData.CustID === null) ? "null" : ("'" + obj.ItemData.CustID + "'")) + "|" + obj.ItemData.dateCreated + "|" + obj.ItemData.amount + "'"

Node js - Mysql query is not executed as coded

i created several sql statements in node.js and now i want to execute them on my db. However, the query string is not executed as coded.
This is my function to generate the query string.
function insertProducts(products) {
if (!connection) {
// Create MYSQL-Connection
console.log('BUILDING connection to DB');
connection = getConnection();
connection.connect();
}
let query = "";
for (let i = 0; i < products.length; i++) {
// Iterate trough the products array and create a sql query
query += "INSERT INTO `tShortDescription`(`ShortDescription`, `Language`) VALUES ('" + products[i].short_description + "', 'DE'); " +
"INSERT INTO `tDescription`(`Description`, `Language`) VALUES ('" + products[i].description + "', 'DE'); " +
"INSERT INTO `tManufacturer`(`Name`) VALUES ('" + products[i].manufactur + "'); " +
"INSERT INTO `tSupplier`(`Name`) VALUES ('" + products[i].supplier + "'); " +
"INSERT INTO `tProduct`(`Sku`, `Title`, `ShortDescriptionId`, `DescriptionId`, `WohlesalePrice`, `SellingPrice`, `Quantity`, " +
"`ManufacturerId`, `SupplierId`, `Ean`) VALUES ('" + products[i].sku + "', '" + products[i].name + "', " +
"(SELECT id FROM tShortDescription WHERE ShortDescription = '" + products[i].short_description + "' LIMIT 1), " +
"(SELECT id FROM tDescription WHERE Description LIKE '" + products[i].description + "' LIMIT 1), " +
products[i].wholesale_price + ", " + products[i].selling_price + ", " + products[i].quantity + ", " +
"(SELECT id FROM tManufacturer WHERE Name = '" + products[i].manufactur + "' LIMIT 1), " +
"(SELECT id FROM tSupplier WHERE Name = '" + products[i].supplier + "' LIMIT 1), " + products[i].ean + "); ";
for (let j = 0; j < products[i].categories.length; j++) {
// Ad all categories to query
query += "INSERT INTO `rtCategory`(`ProductId`, `CategoryId`) " +
"VALUES ((SELECT `Id` FROM `tProduct` WHERE sku = '" + products[i].sku + "' LIMIT 1), " +
"(SELECT `Id` FROM `tCategory` WHERE Id = " + products[i].categories[j].src + " LIMIT 1)); "
for (let c = 0; c < products[i].images.length; c++) {
// Ad all images to query
query += "INSERT INTO `tImage`(`Url`) VALUES ('" + products[i].images[c].src + "'); " +
"INSERT INTO `rtImage`(`ProductId`, `ImageId`) " +
"VALUES ((SELECT `Id` FROM `tProduct` WHERE sku = '" + products[i].sku + "' LIMIT 1), " +
"(SELECT `Id` FROM `tImage` WHERE url = '" + products[i].images[c].src + "' LIMIT 1)); "
}
}
}
query = query.replace(/[\n\r\t]/g,);
if (query != "") {
// Create new Product in DB
return new Promise((resolve, reject) => {
connection.query(query, function (error, results, fields) {
if (error) { console.log(error) };
console.log('INSERTING successful');
resolve(results);
});
});
} else {
console.log('There are no new products to insert in db');
}
}
If i console.log(query) (before the query is ecexuted on my db) and execute the string directly in php myadmin, everything works fine but if i execute the query in code like connection.query(query, function (error, results, fields)....., i got several errors.
Error msg in terminal:
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO `tDescription`(`Description`, `Language`) VALUES ('<p><strong>Tantra' at line 1",
sqlState: '42000',
index: 0,
I also get the sql query returned in terminal because of the error, and if i execute this query directly in php myadmin i also get an error ->
SQL query: Documentation
INSERT INTO `rtImage`(`ProductId`, `ImageId`) VALUES ((SELECT `Id` FROM `tProduct` WHERE sku = 'H1500148' LM
IT 1), (SELECT `Id` FROM `tImage` WHERE url = 'https://cdnbigbuy.com/images/H1500148_409897.jpg' LIMIT 1))
MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LM
IT 1), (SELECT `Id` FROM `tImage` WHERE url = 'https://cdnbigbuy.com/images' at line 1
It looks as if the LIMIT is somehow divided ...use near 'LM IT 1)....
I hope you understand where the problem is and someone might have a tip.
Your query is processed as 'LIMIT' it's just a new line in the console where the error showed up.
You should not be using string concatenation (or even template literals) for SQL queries under any circumstances because 1. It very likely the source of your problem. 2. It's very dangerous as it allows SQL injection attacks.
Use parameters instead. Here's a example:
connection.query("SELECT * FROM bank_accounts WHERE dob = ? AND bank_account = ?",[
req.body.dob,
req.body.account_number
],function(error, results){});
To read more about SQL injections and placeholders read this article.
Thanks for the helpful tips.
The problem was that I didn't set multiple statements: true in my code. This var is by default false and should be true, otherwise it is not possible to execute several queries once at a request!

How to solve? ER_BAD_FIELD_ERROR: Unknown column 'undefined' in 'field list'

I am trying to insert form data into MySQL database in nodejs using expressjs
When I run my code in command prompt it ran well but when I press the submit button, I got the following errors:
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password:'',
database : 'test'
});
app.get("/", function(req, res){
res.render("home");
});
//when I press submit button it should post the request and render a page to submit route with text "data saved!!"
app.post("/submit", function(req, res){
var q = "Insert into test (ID, name, crash1, crash2, crash3) VALUES (null, '" + req.body.ANR + "', " + req.body.crash1 + ", " + req.body.crash2 + ", " + req.body.crash3 +")";
connection.query(q, function(err){
if(err) throw err
res.render("home", {message: 'data saved!!'});
})
});
I created a table in MySQL Command line
create table xyz(
ID BIGINT AUTO_INCREMENT PRIMARY KEY NOT NULL,
name VARCHAR(100) NOT NULL,
crash1 BIGINT,
crash2 BIGINT,
crash3 BIGINT
);
when I inserted manually it worked!
insert into xyz(ID, name, crash1, crash2, crash3) VALUES (1,'REERE', 2 ,2 ,2);
my error looks like this
You are inserting into test table in your code:
var q = "Insert into test (ID, name, crash1, crash2, crash3) VALUES (null, '" + req.body.ANR + "', " + req.body.crash1 + ", " + req.body.crash2 + ", " + req.body.crash3 +")";
But table name is xyz. You should replace test by xyz and it should work.
And don't pass null in id as well as id is not null.
Please convert crash1, crash2, crash3 into int value:
req.body.crash1 = parseInt(req.body.crash1);
req.body.crash2 = parseInt(req.body.crash2);
req.body.crash3 = parseInt(req.body.crash3);
It should be like:
var q = "Insert into xyz (name, crash1, crash2, crash3) VALUES ('" + req.body.ANR + "', " + req.body.crash1 + ", " + req.body.crash2 + ", " + req.body.crash3 +")";

NodeJS MySQL error

NodeJS code is given below:
app.get('/search', function(req, res){
var keyword = req.query.q;
con.query("SELECT Post_Title, Post_Icon, Post_Cont, Post_Author, Post_Date FROM Posts WHERE Post_Title LIKE '" + keyword + "' OR Post_Icon LIKE '" + keyword + "' OR Post_Cont LIKE '" + keyword + "' OR Post_Author LIKE '" + keyword + "' OR Post_Date LIKE '" + keyword + "' ORDER BY Post_Date ASC", function (err, result) {
    if (err){
console.log("Error on DB SELECT.");
console.log(err);
tellSelectError(req, res);
}else{
console.log("Database selected");
console.log(result);
/*res.render('index', {
info: info,
result: result
});*/
res.json(result);
}
});
});
It send empty json to client browser.
Screenshot is uploaded at: https://i.stack.imgur.com/kpSDA.jpg
Please help.....
This code is working:
SELECT * FROM Posts WHERE Post_ID = " + keyword but I want to use LIKE with all coloums of Posts excluding Post_ID.
console.log(err); logs no error.
Got a news:
When I change the SQL to SELECT * FROM Posts, it correctly returning all raws but SELECT Post_Title, Post_Icon, Post_Cont, Post_Author, Post_Date FROM Posts WHERE Post_Title LIKE '" + keyword + "' OR Post_Icon LIKE '" + keyword + "' OR Post_Cont LIKE '" + keyword + "' OR Post_Author LIKE '" + keyword + "' OR Post_Date LIKE '" + keyword + "' ORDER BY Post_Date ASC is not working as expected.
You need to wrap the values you pass to the query in quotes. So the correct syntax for you should be:
"SELECT Post_Title, Post_Icon, Post_Cont, Post_Author, Post_Date
FROM Posts
WHERE Post_Title LIKE '" + keyword + "' OR Post_Icon LIKE '" + keyword + "' OR Post_Cont LIKE '" + keyword + "' OR Post_Author LIKE '" + keyword + "' OR Post_Date LIKE '" + keyword + "' ORDER BY Post_Date ASC"
Note: LIKE is an operator that is used instead of = to search for a value inside a field. = will try to match the full field. To do so LIKE use a wildcard (%) in three different options:
%keyword the value ends with keyword;
keyword% the value begins with keyword;
%keywords% the value contains somewhere the keyword
If you don't use the wildcard it is useless to use LIKE

NodeJs - mysql insert error

I have the following insert query:
connection.query('INSERT INTO `items` (`gameID`, `userID`, `bidID`, `value`, `imageUrl`, `itemName`) VALUES (' + gameID + ', 8, ' + rows.insertId + ', 3, https://steamcommunity-a.akamaihd.net/economy/image/class/730/' + ourItems[i].classid + '/150fx125f, ' + ourItems[i].market_name + ')', function(err, rows, fields) {
if (err) throw err;
});
I'm getting the following error however:
Any ideas?
You should work on your strings and concatenations:
connection.query("INSERT INTO `items` (`gameID`, `userID`, `bidID`, `value`, `imageUrl`, `itemName`)
VALUES ('" + gameID + "',
8,
'" + rows.insertId + "',
3,
'https://steamcommunity-a.akamaihd.net/economy/image/class/730/" + ourItems[i].classid + "/150fx125f',
'" + ourItems[i].market_name + "'
)", function(err, rows, fields) {
if (err) throw err;
});
This should be syntactically correct.
You should never build queries using that kind of concatenation.
You most likely will end up in a query that might break in future or even opens a possibility for sql injection.
If you use the mysql module then you should think over using the escape feature that are build in with the module (Escaping query values):
connection.query('INSERT INTO `items` SET ?',
{
gameID: gameID,
userID: 8,
/* ... */
imageUrl: 'https://steamcommunity-a.akamaihd.net/economy/image/class/730/' + ourItems[i].classid + '/150fx125f'
/* ... */
}, function(err, rows, fields) {
if (err) throw err;
});