In node js I used to run a LIKE statement query to get data from MYSQL database, however, due to poor performances I have updated my query to use full-text search ("where match AGAINST" statement). I tried to run the query with a "?" placeholder or by using escape() method (to avoid sql injection) but with no success. The query only ran successfully without having the "?" placeholder or escape() method.
I have looked up other answers provided but couldn't find a solution to this.
code works - sql-injection vulnerable
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") code doesn't work - added ? placeholder to avoid sql injection
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") Error message that I'm getting with second query:
Failed to query for description: Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''(\'Clorox\')'' at line 1
Is there any way to use mysql full-text search in node js and also have a way to avoid sql injection?
Thanks in advance for any suggestions!
EDIT Thanks for the answer, this is what worked for me.
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")
+ "'" + req.query.Name + "'"- this is sql-injection vulnerability! see: xkcd.com/327WHERE descr MATCH ??