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){
Related
I have made a simple query using nodejs and mysql. The issue is whenever the user inputs product details containing any single quote an error occurs. How do i replace or remove such error.
You must escape the input values as reported in the documentation of mysql for nodejs using escape function.
From my understanding you want to Escape query values when you perform the mysql operations i don't know which mysql driver you are using but i will suggest some solutions with the node.js driver for mysql.
On this nodejs mysql drive builtin mechanism for Escaping query values.In order to avoid SQL Injection attacks, you should always escape any user provided data before using it inside a SQL query. You can do so using the mysql.escape(), connection.escape() or pool.escape() methods:
Caution These methods of escaping values only works when the
NO_BACKSLASH_ESCAPES SQL mode is disabled (which is the default state
for MySQL servers).
var userId = 'some user provided value';
var sql = 'SELECT * FROM users WHERE id = ' + connection.escape(userId);
connection.query(sql, function (error, results, fields) {
if (error) throw error;
// ...
});
Alternatively, you can use ? characters as placeholders for values you would like to have escaped like this:
connection.query('SELECT * FROM users WHERE id = ?', [userId], function (error, results, fields) {
if (error) throw error;
// ...
});
Multiple placeholders are mapped to values in the same order as passed. For example, in the following query foo equals a, bar equals b, baz equals c, and id will be userId:
connection.query('UPDATE users SET foo = ?, bar = ?, baz = ? WHERE id = ?', ['a', 'b', 'c', userId], function (error, results, fields) {
if (error) throw error;
// ...
});
This looks similar to prepared statements in MySQL, however it really just uses the same connection.escape() method internally.I hope this will helps you.
node-mysql this is a good library which auto escape query values check it out https://github.com/mysqljs/mysql#escaping-query-values
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.
I am trying to perform a post call in node js, i am testing it through post but i am not able to retrive data,
my node code,
exports.login = function( req, res ) {
console.log("Params:"+req.body.email);
//console.log('email:'+params.email);
connection.query('SELECT * FROM profile where email ='+req.body.email,function(error,result,rows,fields){
if(!!error){console.log(error)
console.log('fail');
}else{
console.log(result);
res.send(result);
}
// }
});}
my routes,
router.post('/login',cors(), admin.login);
i am getting fail and my error 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 '#gmail.com' at line 1]
my input through postman
{"email":"s#gmail.com"}
Don't build the query string directly, this leaves you open to injection attacks and also chokes on certain characters, as you are experiencing here. Use a placeholder like so:
var query = "select * from profile where email = ?";
connection.query(query, [req.body.email], function(error,result,rows,fields) {
...
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));
Finally i move forward from postgresql 9.1 to postresql 9.3 that supports JSON data type. Then the same code function properly.
However i think that what i want to do in the first place can be done... if someone know how i still want to know.
Enviroment
node v0.10.28
pg v3.3.0
postgresql 9.1
I got this insert query
INSERT INTO sessions(sid, user_id, session_object) VALUES ('id1', 1, '{"id":"fX2HkXYLclB","data": testing"}') RETURNING session_id
When testing it from pgAdmin (or command line) it works fine, but when my app try to run it from pg.client.query it try to turn the object as a string saving "[object object]". Here is the node code:
var session = {"id":"fX2HkXYLclB","data": "testing"};
var sql = 'INSERT INTO sessions(sid, user_id, session_object) VALUES (\'id1\', ' +
' 1, \''+JSON.stringify(session)+'\' ) RETURNING session_id';
console.log(sql);
client.query(sql, function(err, info) {
if(err) {
return addSessionCB(err, null);
}
return addSessionCB(null, info.rows[0].session_id);
});
After runing the application and testing the query manually on pg_admin the table show this 2 results.
session_id | sid | user_id | session_object | active
------------+-------------+---------+---------------------------------------+---------
1 | fX2HkXYLclB | 1 | [object Object] | t
2 | fX2HkXYLclB | 1 | {"id":"fX2HkXYLclB","data": "testing"}| t
(2 filas)
So, the question is ¿what im doing wrong with the pg.query?
Adding the original code, the code before is simplified for readability.
function addSession(session, addSessionCB) {
log.log('debug', '[PSQL]Add new session on DB. \nsession: '+ session.id +
'\nuser:'+ session.data.user);
function executeAddSessionQuery(user_id){
var sql = 'INSERT INTO sessions(sid, user_id, session_object) VALUES (\'' +
session.id + '\', '+user_id+', \''+JSON.stringify(session)+'\' ) ' +
'RETURNING session_id';
log.log('debug', '[PSQL]Adding session: '+session.id+' for user_id: '+
user_id+'\nSQL: '+sql);
client.query(sql, function(err, info) {
if(err) {
log.log('debug', '[PSQL]Error adding new session. \n'+err);
return addSessionCB(err, null);
}
return addSessionCB(null, info.rows[0].session_id);
});
};
//to save session we need to know user id
getUserByName({name: session.data.user},
function getUserByNameCB(err, user_result){
if(err || !user_result){
//if error or not result we try to save new user
log.log('debug', '[PSQL]Associated user not found. Creating a new ' +
'user entry. ');
addUser({name: session.data.user},
function addUserCB(err, newUserID){
if(err){
log.log('warn', '[PSQL]Session user didn\'t exists and cannot be ' +
'added to DB');
return addSessionCB(err, null);
}
executeAddSessionQuery(newUserID);
});
} else {
//if the user exist we use his id.
executeAddSessionQuery(user_result.user_id);
}
});
}
The node postgres module has another form of query; where the 2nd parameter is an array of objects. So in your case
var sql = 'INSERT INTO sessions(sid,user_id,session_object) VALUES ($1,$2,$3) RETURNING session_id';
var values = [id1,1,JSON.stringify(session)];
and then follow that up with
client.query(sql,values,function(err,info) {
...
This also has the added benefit of guarding against SQL injection attacks.