I am uploading images using nodejs
My query is like:
var user = req.body;
var imgurl=projectDir +"/uploads/"+req.files.displayImage.name;
var sql= "INSERT INTO users values('','"+user.name+"','"+user.email+"','"+user.user+"','"+user.pass+"','"+imgurl+"',now())";
Everything goes right, accept one that when it inserts imgurl it does not parse it,
My project directory is D:\node
also I get it in projectDir =D:\node
But it will insert in database like:
D:
ode/uploads/canvas.png
I understand that it converts \n to new line,
So, my question is how to prevent this and what should I do for both single and double quotes insertion?
Thanks.
You should consider preparing your queries using the '?' syntax (https://github.com/felixge/node-mysql#preparing-queries).
var sql= "INSERT INTO users SET ?";
// Connection attained as listed above.
connection.query( sql, { name:user.name, email:user.email, user:user.user, pass:user.pass, image:imgurl, timestamp:now()}, function(err, result){
// check result if err is undefined.
});
Using this pattern, node-mysql will do all the escaping and safety checks for you.
Hope this helps...
Escape them using \ as such \\n or \" \' etc.
Here's a related question that answers your query. The method:
function mysql_real_escape_string (str) {
return str.replace(/[\0\x08\x09\x1a\n\r"'\\\%]/g, function (char) {
switch (char) {
case "\0":
return "\\0";
case "\x08":
return "\\b";
case "\x09":
return "\\t";
case "\x1a":
return "\\z";
case "\n":
return "\\n";
case "\r":
return "\\r";
case "\"":
case "'":
case "\\":
case "%":
return "\\"+char; // prepends a backslash to backslash, percent,
// and double/single quotes
}
});
}
You can store the mysql_real_escape_string() function as a separate module and require it before usage or directly insert it into the .js file that will be using it.
You could use it as shown below:
var sql= "INSERT INTO users values('','"+user.name+"','"+user.email+"','"+user.user+"','"+user.pass+"','"+mysql_real_escape_string(imgurl)+"',now())";
Uggh, escape all the backslash and quotes in your query string. Always use connection.escape
var mysql = require('mysql');
var connection = mysql.createConnection(...);
var userId = 'some user provided value';
var sql = 'SELECT * FROM users WHERE id = ' + connection.escape(userId);
connection.query(sql, function(err, results) {
// ...
});