我正在使用Node.js创建一个Discord bot。我的一些代码如下所示:
Meteor.startup()
人们说我放入var info = {
userid: message.author.id
}
connection.query("SELECT * FROM table WHERE userid = '" + message.author.id + "'", info, function(error) {
if (error) throw error;
});
的方式并不安全。我怎样才能做到这一点?一个例子?
答案 0 :(得分:7)
最好的方法是使用预准备语句或查询(链接到NPM mysql
模块的文档:https://github.com/mysqljs/mysql#preparing-queries)
var sql = "SELECT * FROM table WHERE userid = ?";
var inserts = [message.author.id];
sql = mysql.format(sql, inserts);
如果准备好的语句不是一个选项(我不知道为什么它不会),那么一个穷人防止SQL注入的方法是逃避所有用户提供的输入,如下所述:https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet#MySQL_Escaping
答案 1 :(得分:1)
使用准备好的查询;
var sql = "SELECT * FROM table WHERE userid = ?";
var inserts = [message.author.id];
sql = mysql.format(sql, inserts);
您可以找到更多信息here。
答案 2 :(得分:1)
以下是有关如何正确转义任何用户提供的数据以防止SQL注入的文档:https://github.com/mysqljs/mysql#escaping-query-values。
array (4)
id => 36
count => 1
product => Nette\Database\Table\ActiveRow #7c60
table private => Nette\Database\Table\Selection #739c
data private => array (3)
product_id => 36
price => 219.0
supplier_id => 3
dataRefreshed private => FALSE
names => array (1)
en => "Product 1" (9)
array (4)
id => 180
count => 1
product => Nette\Database\Table\ActiveRow #938b
table private => Nette\Database\Table\Selection #a5f0
data private => array (3)
product_id => 180
price => 375.0
supplier_id => 4
dataRefreshed private => FALSE
names => array (1)
en => "Product 2" (9)
array (4)
id => 309
count => 1
product => Nette\Database\Table\ActiveRow #4c67
table private => Nette\Database\Table\Selection #8f56
data private => array (3)
product_id => 309
price => 40.0
supplier_id => 5
dataRefreshed private => FALSE
names => array (1)
en => "Product 3" (9)
就足够了。