Node js - Mysql query is not executed as coded - mysql

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!

Related

My query works in MySQL workbench and phpmyadmin but not in node.js

I'm trying to get a query to work in node.js but I can't get it to work. I've tested it in MySQL workbench and in phpmyadmin, and the query works in both. Can someone see what the error is?
I've tried adding backticks to the query, didn't work. Tried to use " instead of ` to start the query, didn't work.
app.get('/meetings/add', (req, res) => {
const { meetingsubject, meetingdescription, bulletpoints, bulletpointslength } = req.query;
var bulletPointQuery = " INSERT INTO `bulletpoints` (`idmeeting`, `bulletpointname`) VALUES ";
var allBulletPoints = bulletpoints.split(',');
for(var i = 0; i < bulletpointslength; i++){
if(i === bulletpointslength - 1){
bulletPointQuery = bulletPointQuery + "(LAST_INSERT_ID(), '" + allBulletPoints[i] + "');";
}else {
bulletPointQuery = bulletPointQuery + "(LAST_INSERT_ID(), '" + allBulletPoints[i] + "'),"
}
}
const insertMeeting = "BEGIN; INSERT INTO `meetings` (`meetingsubject`, `meetingdescription`) VALUES ('" + meetingsubject +"', '" + meetingdescription + "');" + bulletPointQuery + "COMMIT;";
connection.query(insertMeeting, (err, results) => {
if(err){
console.log(err);
return res.send(err);
}else{
console.log("yup");
res.send("sucessfully added meeting");
}
});
});
this is the error:
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 meetings (meetingsubject, meetingdescription) VALUES ('yayeet'' at line 1",
sqlState: '42000',
index: 0,
sql: "BEGIN; INSERT INTO meetings (meetingsubject, meetingdescription) VALUES ('yayeet', 'yaeter'); INSERT INTO bulletpoints (idmeeting, bulletpointname) VALUES (LAST_INSERT_ID(), 'yeet (07:30)'),(LAST_INSERT_ID(), 'wwee (07:30)');COMMIT;"
EDIT
The query i'm trying to work with:
BEGIN;
INSERT INTO `meetings` (`meetingsubject`, `meetingdescription`)
VALUES ('yayeet', 'yaeter');
INSERT INTO `bulletpoints` (`idmeeting`, `bulletpointname`)
VALUES (LAST_INSERT_ID(), 'yeet (07:30)'),
(LAST_INSERT_ID(), 'wwee (07:30)');
COMMIT;

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

Matching on empty strings, not nulls, in a MySQL column

I can't get the right syntax - I'm trying to match on the column as an empty string, not a null. I've tried delimiting the string all number of ways, using single double quotes.
containerRefNo = "\"\"";
ps = getConnection().prepareStatement(
"delete from inumber_join where container_no = ?");
The error I receive is
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'from inumber_join where container_no = '""''
When using a parameterized query you don't need to include any delimiters in the parameter value. Simply using ps.setString(1, ""); works fine for me.
That is, ...
// setup
try (Statement st = conn.createStatement()) {
st.executeUpdate(
"CREATE TEMPORARY TABLE inumber_join_temp (" +
"id INT AUTO_INCREMENT, " +
"container_no VARCHAR(10) NULL, " +
"PRIMARY KEY (id)" +
")");
st.executeUpdate(
"INSERT INTO inumber_join_temp (container_no) " +
"VALUES (null), (''), (null), (''), (null)");
}
// test
String sql =
"SELECT COUNT(*) AS n " +
"FROM inumber_join_temp " +
"WHERE container_no = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, ""); // search for empty string
try (ResultSet rs = ps.executeQuery()) {
rs.next();
System.out.println(rs.getInt(1));
}
}
... returns
2

Querying multiple rows using node-mysql

This issue pertains to node-mysql.
I seem to be having a problem with the following code, and it seems to be related to the use of user defined variables. The rendered query runs fine inside of any mysql IDE, returning multiple records. However when executed by node-mysql, it only returns a single record.
I've verified that eliminating the WHERE clause specifying T3.gender_rank creates predictable results in both node-mysql and my mysql IDE.
Has this issue been raised before, or is it something that I'm doing wrong?
var mysql = require('mysql'); // Establish SQL Support
var sql =
"select team, `div`, sum(points) AS teampoints "+
"from ( "+
" select "+
" *, "+
" (#genderRank := CASE WHEN #genderTMP <> gender THEN 1 ELSE #genderRank+1 END) AS gender_rank, "+
" (#genderTMP := gender) AS _gt "+
" from ( "+
" select * "+
" from racepoints "+
" WHERE "+
" ltrim(rtrim(race)) = '"+data.eventName+"' AND "+
" racedate = '"+getSimpleDate(new Date(data.eventStart))+"' "+
" ORDER BY team,gender,points DESC "+
" ) T1, "+
" (select #genderRank:=0 AS gender_rank_start) T2 "+
") T3 "+
"WHERE "+
" (T3.gender_rank <= 4 AND rtrim(ltrim(`div`)) = 'D2') OR "+
" (T3.gender_rank <= 3 AND rtrim(ltrim(`div`)) = 'D1') "+
"GROUP BY team, `div` "+
"ORDER BY `div`, teampoints DESC, team";
var db = new mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'admin',
database : 'nps',
multipleResults : true
});
db.connect();
db.query(
sql,
function(err,rows,fields){
if(err){
console.log(err);
return;
}
console.log(rows);
}
);
db.end();
The SQL database file is also available here: https://snipt.net/download/dde8b4b5ce8cd5fca21ac2334bae634f/-5369.sql
Instead of directly adding your variables to the sql string, let the mysql package do it for you. This usually solves problems like this one and additionally protects against SQL injection.
This is done using question marks (one for every variable) followed by an array of variables.
For example
connection.query('SELECT * FROM users WHERE id = ?', [userId], function(err, results) {
// ...
});