mysql - 如何使用escape()方法在节点中使用mysql全文搜索?
问题描述
在节点 js 中,我曾经运行 LIKE 语句查询以从 MYSQL 数据库中获取数据,但是,由于性能不佳,我已将查询更新为使用全文搜索(“where match AGAINST”语句)。我尝试使用“?”运行查询。占位符或使用 escape() 方法(以避免 sql 注入)但没有成功。查询仅成功运行而没有“?” 占位符或 escape() 方法。
我查看了提供的其他答案,但找不到解决方案。
代码有效- sql-injection 易受攻击
function (req,res,next) {
/// req.query.Name is coming from user input of a form
const queryString = "Select idx, descr, price, product_img,\
stock, available from prod.product_list_details where match descr \
against" + "(" + "'" + req.query.Name + "'" + ")"
connection.query(queryString, (err, rows, fields) => {
if (err) {
console.log("Failed to query for description: " + err)
res.sendStatus(500)
return
}
console.log("I think we fetched products successfully")
代码不起作用-添加?避免sql注入的占位符
function (req,res,next) {
///productDescription is from user input of a form
var productDescription = "(" + "'" + req.query.Name+ "'" + ")"
const queryString = "Select idx, descr, price, product_img, stock,\
available from prod.product_list_details where match descr against ?"
connection.query(queryString, productDescription,
(err, rows, fields) => {
if (err) {
console.log("Failed to query for description: " + err)
res.sendStatus(500)
return
}
console.log("I think we fetched products successfully")
我在第二个查询中收到的错误消息:
无法查询描述:错误:ER_PARSE_ERROR:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的 ''(\'Clorox\')'' 附近使用正确的语法
有没有办法在node js中使用mysql全文搜索,也有办法避免sql注入?
在此先感谢您的任何建议!
编辑 感谢您的回答,这对我有用。
function (req,res,next) {
var userInput = req.query.Name ///values to search
var modifiedUserInput = userInput.replace(/ /g,"+")
var productDescription = "'+" + modifiedUserInput+ "'"
const queryString = "Select idx, descr, price, product_img, stock, available from \
prod.product_list_details where match descr against (? IN BOOLEAN MODE)"
connection.query(queryString, productDescription,
(err, rows, fields) => {
if (err) {
console.log("Failed to query for description: " + err)
res.sendStatus(500)
return
}
console.log("I think we fetched products successfully")
解决方案
使用占位符时,请务必注意这些仅用于数据并且不能包含语法元素,这将导致解析错误。
在您的情况下,这意味着查询应采用以下形式:
WHERE MATCH (descr) AGAINST (? IN BOOLEAN MODE)
where?
表示要包含的数据,并且只有数据。当您放入括号时,它有效地扩展为:
WHERE MATCH (descr) AGAINST '(...)'
这破坏了语法,因为括号现在位于数据内部,而不是围绕数据。
对于占位符是数据一部分的LIKE
位置%
,您可以像这样将它们放入:
WHERE x LIKE ?
在其他情况下,您可以这样做:
WHERE x LIKE CONCAT('%', ?)
如果您更喜欢在程序集数据库端进行。
在任何情况下,使用带有占位符值的准备好的语句非常重要,因此掌握这一点很重要,而且您朝着这个方向努力真是太好了。
希望能帮助你到达你想去的地方。
推荐阅读
- django - 如何将模型用户中的对象过滤到列表中
- mapkit - Xcode 11,iOS 13.2 - “libMobileGestalt MobileGestalt. c:1647: 无法检索区域信息”地图错误
- r - ~/.R/Makevars/ 是什么/在哪里。文件?
- python - 为什么 pytesseract 不能正确识别?
- applescript - 尝试循环列表,以便打印出每个偶数
- maven - 如何将特定版本的 jar 包含到 Uber jar 中?
- typescript - 如何映射定义为 FieldValue 的 Firestore 数组值
- java - Java早期阶段的UNO游戏问题
- unity3d - Collider2D 碰撞在 Unity 中不起作用
- r - 如何按数字向量和字符向量对数据帧进行排序