2

我正在uploading images使用nodejs

query的就像:

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())";

一切正常,除非它插入imgurl它不parse它,

project directory也是D:\node 我得到它projectDir =D:\node

但它会insertdatabase

D:
ode/uploads/canvas.png

我知道它转换\nnew line,

那么,我question是如何防止这种情况的,我该怎么办both single and double quotes insertion

谢谢。

4

4 回答 4

5

\使用as 这样\\n\" \'etc来逃避它们。

这是一个回答您查询的相关问题。方法:

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
        }
    });
}

您可以将该mysql_real_escape_string()函数存储为一个单独的模块,并在使用前将其 require,或者直接将其插入将使用它的 .js 文件中。您可以使用它,如下所示:

var sql= "INSERT INTO users values('','"+user.name+"','"+user.email+"','"+user.user+"','"+user.pass+"','"+mysql_real_escape_string(imgurl)+"',now())";
于 2013-03-15T11:08:52.340 回答
5

您应该考虑使用“?”来准备您的查询。语法(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.
});

使用此模式,node-mysql 将为您完成所有转义和安全检查。

希望这可以帮助...

于 2013-10-20T05:04:15.487 回答
0

呃,转义查询字符串中的所有反斜杠和引号。始终使用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) {
  // ...
});
于 2013-03-15T11:18:38.850 回答
0
var mysql      = require('mysql');
var connection = mysql.createConnection({
 host     : 'localhost',
 user     : 'root',
 password : '',
 database : '*****'
});

connection.connect(function(err){
 if(!err) {
  console.log("Database is connected");
 } else {
  console.log("Error while connecting with database");
 }
});

var message  = req.body.message;
var user_id  = req.body.user_id;
var sql = "INSERT INTO users(user_id, message) VALUES ('"+user_id+"', "+connection.escape(message)+")";
connection.query(sql, function(err, result) { });
于 2019-07-23T12:13:58.737 回答