我使用node-mysql作为mysql连接器,变量中的大部分值都是由用户发送的,所以我使用占位符来阻止sql注入。在下面的代码中" req.params.TableName"和" req.params.order"由用户发送,表和订单变量值从前端输入,值如下。
变量中的值将为:
req.params.TableName = "officers"
req.params.order = asc OR desc
查询:
var table = [req.params.TableName, req.body.order];
var query = 'SELECT `officer_id` FROM ?? ORDER BY officer_id ??';
fullquery = mysql.format(query, table);
问题:
上面的代码生成以下查询,由于围绕ASC的反引号,我给出了语法错误,如何删除这些反引号?感谢
SELECT `officer_id` FROM `officers` ORDER BY officer_id `ASC`;
答案 0 :(得分:1)
我不知道Mysql Node是如何工作的,但我会给你一个例子。
req.params.TableName = 'officers';
req.params.order = asc || desc;
//Insert statement
var newOrder = encodeOrder({
name: "'awesome'"
price: 1000
})
var query = "INSERT into orders values ??, ??";
fullquery = mysql.format(query, [newOrder.name, newOrder.price]);
//Like statement
var query = "SELECT * FROM orders WHERE orders.name LIKE ?";
fullquery = mysql.format(query, [encodeURIComponent(order.name)]);
//DONT KNOW HOW TO EXECUTE >.<
var result = [{name: "\'awesome\'", price: 1000}]
for (var index = 0; index < result.length; index++) {
result[index] = decodeOrder(result[index]);
}
//Result is now
// [{name: 'awesome', price: 1000});
//Can be reused for several objects ofcourse
function decodeOrder(order) {
var result = {};
//My expectation is that order is a object.
Object.keys(order).forEach(function (key) {
result[key] = decodeURIComponent(order[key])
}
return result;
}
//Can be reused for several objects ofcourse
function encodeOrder(order) {
var result = {};
//My expectation is that order is a object.
Object.keys(order).forEach(function (key) {
result[key] = encodeURIComponent(order[key])
}
return result;
}
这不在我的脑海里。所以不知道这是否执行,但希望你能得到这个想法
答案 1 :(得分:0)
试试这个
req.params.TableName = 'officers';
req.params.order = asc || desc;
var table = [req.params.TableName, req.body.order];
var query = "SELECT `officer_id` FROM ?? ORDER BY officer_id ??";
fullquery = mysql.format(query, table);
答案 2 :(得分:0)
找到答案
只需要使用
$newCarId
我将从括号内的字符串中删除每个特殊字符。