Not able to insert data into table using Nodejs - mysql

exports.creategroup= function(callback,name,email,firstname)
{
// var connection=pool.getConnection();
var connection=connect();
console.log(email);
console.log(firstname);
var query="CREATE TABLE "+name+"(membername varchar(50) NOT NULL,email varchar(50) NOT NULL)";
var query1="INSERT INTO'"+name+"'(membername,email) VALUES('"+email+"','"+firstname+"')";
console.log(query);
connection.query(query,function(err,result){
if(err)
{
console.log("ERROR:"+err.message);
}
else
{
if(result.length!==0)
{
console.log("DATA : "+JSON.stringify(result));
callback(err, result);
}
else
{
callback("Invalid Username", result);
}
}
//pool.returnConnection(connection);
});
//The insert into query gives an error. I can't figure out what syntax error i have made. Could someone please help. The table is being created. The error I am facing in the insert is
ERROR:ER_PARSE_ERROR: 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 ''sad'(membername,email) VALUES('hunur','Sachin
Mallikarjun')' at line 1
here sad was passed as the argument for table name

You've put the table Name in ' ticks, that's not valid. Below will work:
var query1="INSERT INTO "+name+" (membername,email) VALUES('"+email+"','"+firstname+"')";
Please note that you absolutely shouldn't run a query like this as it is vulnerable to mysql injection. Use the escaped query node-mysql offers instead.
var query = "INSERT INTO ?? (??,??) VALUES (?,?)";
var values = [name,'membername','email',firstname,email];
mysql.query(mysql.format(query, values), function(err,result,tableInfo){/*...*/})
Like this, node-mysql prepares the query for you. Every ?? represents a table or column name while every ? stands for a value to be inserted. You can verify this by
console.log(mysql.format(query,values));

Related

MYSQL stops function when no data is found? (node.js)

I am getting som data from my MYSQL database. It checks for the email and date to match the users email and chosen date, then it gets the matching rows data. It all works well if I use a date that exists in the table, but when I use a date that does not exists, I get a ER_PARSE_ERROR.
It looks like this:
let date = 27/09/2019
let sql = `SELECT weigh, temp, length, cat, date FROM reps WHERE email = 'test#gmail.com' AND date = ?`;
connection.query(sql, [date], (error, result, fields) => {
if (error) throw error;
//here I do some stuff
When the date is not in the database, I get this:
Error: ER_PARSE_ERROR: 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 ')'
If there is no date, it now crashes my whole function. Instead I just want it to not get anything and keep the function going.
I tried below but it is still crashing:
if (error) {
send.response('nothing');
}
Any idea how to solve this?
This is finally solved. The reason I got the ER_PARSE_ERROR: was because I hade some functions that relied on the MySQL output. When no rows from MySQL was shown, the error occurred. I solved it by saying if nothing then end response. This is the code:
if (error) { throw error;
} else if (!result.length) { //Checks if no results, then ends the response without doing anything, before it tried to do things when there was no result which caused the error.
return console.log('Date or email does not match any database rows');
response.end();
}

Insert JSON object data to MySQL using Node.JS

I want insert a JSON object into MySQL in Node.js server, this is the code
let id = 1
let date = new Date().toJSON().slice(0,10).replace(/-/g,'/');
let sql ='INSERT INTO case_record (case_details,gen_date,case_id) VALUES('+caseDetails+','+date+','+id+')'
console.log(sql)
con.query(sql,function(err, result, fields){
if(err) throw err;
res = result;
console.log(res)
});
This is the caseDetails data
let caseDetails = {
caseData,
patData,
notifData,
primecData,
refData}
Each of the object in the caseDetails is JSON object also.
When I excute, the error return is
Error: ER_PARSE_ERROR: 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 '[object Object],2019/04/22,1)' at line 1
How to fix this problem?
Your SQL syntax is wrong to cause parsing error.
Why don't u follow this correction?
...
let sql ='INSERT INTO case_record(case_details,gen_date,case_id) VALUES(?,?,?)';
con.query(sql, [caseDetails,date,id] ,function(err, result, fields) {
...
});
Hope to get helped.

Node.js MySQL mass insert operation fails

Below is my code for mass insert into my MYSQL Db
connectionPool.getConnection(function(err, connection){
if(err) {
winston.log('info', '------- ERROR while getting connection: ' + err.message);
connection.release();
return;
}
connection.query('INSERT INTO PollOptions (idPollOption, Option, PollId) values ?', [pollOptionsArray], function(err, rows){
if(err) {
winston.info('info', '----------------------- ERROR: ' + err);
connection.release();
return;
}
connection.release();
});
});
Where the pollOptionsArray is
[
["POPE1lrKXMy9Q","Adam","POLL4yrFXzkcX"],
["POPVy-StXGJcm","Mike","POLL4yrFXzkcX"],["POPNkMSFmGy97","Lucy","POLL4yrFXzkcX"]
]
The database table has the following columns
idPollOption, Option, PollId (all VARCHAR)
It gives me the following error:
ERROR: Error: ER_PARSE_ERROR: 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 'Option, PollId) values ('POPE1lrKXMy9Q',
'Adam', 'POLL4yrFXzkcX'), ('POPVy-StXGJ' at line 1
I even tried to hardcode my sql input like this:
var temp = [
['123', 'demian#gmail.com', 'POLLVJsBGIjYQ'],
['345', 'john#gmail.com', 'POLLVJsBGIjYQ'],
['567', 'mark#gmail.com', 'POLLVJsBGIjYQ'],
['678', 'pete#gmail.com', 'POLLVJsBGIjYQ']
];
But it still gives me the same error. I don't understand what I am doing wrong. Clearly my SQL syntax is incorrect at the values but what is the remedy?
I even tried to remove the '[]' in the pollOptionsArray and it gives me the same error.
Any idea what is going on here?
So there was no issue with my syntax. The problem was the column named "Option".
Apparently "Option" is a reserved keyword in MySQL and since I used it to name my column, it was giving me trouble.

Node Js mySQL updating multiple rows with array of arrays

I've got a dynamically assigned number of rows which I need to update. I created an array of arrays to keep all of those values and send them in one query. Each array contains three values A - a value which I want to update and B, C - keys necessary to recognize which row need to be updated.
var arrData = [];
arrData[0] = [43,54,67];
arrData[1] = [56,68,75];
arrData[2] = [43,67,75];
...
var query = "UPDATE my_table SET A_row = ? WHERE B_row = ? AND C_row = ?";
connection.query(query,[arrData], function(err,response){
if(err)
{
console.log(err)
}
else{ ... });
But then I get this error:
Error: ER_PARSE_ERROR: 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 '? AND C_row = ?' at line 1
What do I do wrong here?
Each ? needs to resolve to an actual value. So you need a loop with a counter to set the index on the array and call the query ... something like,
...
for(cnt=0;cnt< length;cnt++) {
connection.query(query,arrData[cnt], function(err,response){
if(err){console.log(err)
else{ ... });

Error executing UPDATE

I'm having a little trouble performing an update query with the node mysql2 module. I'm preparing the query using the '?' placeholder and then passing in the values like so;
socket.on('connection', function(client){
[...]
client.on('userjoin', function(username, userid){
run_db_insert("UPDATE users_table SET clientid = ? WHERE user = ?", [client.id, userid], function(){
console.log(client.id + ' <=> ' + userid);
});
[...]
});
Unfortunately, this is raising an error;
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 ''12345678' WHERE userid = ?' at line 1
The data isn't reflected in the database. For some reason, the code doesn't appear to be picking up the second question mark placeholder and so it's not passing the correct value (i.e. it's trying to find the userid of ?).
If I change the code to this;
run_db_insert("UPDATE users_table SET clientid = ? WHERE user = '" + userid + "'", [client.id], function(){
...then the update runs without error and is reflected in the DB. If I console.log both client.id and userid, the console correctly reflects these values.
My run_db_insert function is as follows;
function run_db_insert(sql, args, callback){
var mysql = svc_mysql2.createConnection({
// connection details
});
mysql.connect(function(err){
if(err){
console.log('Error connecting to DB: ' + err);
}
});
mysql.query(sql, [args], function(err){
if (err){
console.log(err);
return;
}
callback();
});
mysql.end();
};
I've had no problems performing SELECT or INSERT queries using multiple '?' placeholders (with a slightly modified function that has result in the line 11 of that function and then returns that in the callback), but I'm finding that UPDATE isn't correctly assigning all the parameters I'm passing in to it.
I think your problem is that you're wrapping your query replacement values in another array, so [[client.id, userid]] is being passed to mysql.query().
Try changing:
mysql.query(sql, [args], function(err){
to:
mysql.query(sql, args, function(err){