I have an endpoint in my express app that accepts POST data (json). I'd like use the data to query a MySQL database safely. Does escaping and altering my string leave me vulnerable to exploitation?
I need to alter the string that comes in from the request because I wan't to insert a '%' before the closing single quote in the LIKE clause.
var searchTerm = mysql.escape(req.body.firstName)
var newStr = "'" + searchTerm.substring(1, searchTerm.length - 1) + "%'"
// Example: 'alex' => 'alex%'
My query is:
SELECT * FROM tbl WHERE col LIKE " + newStr + " ORDER BY key
This works, but is there a preferred or safer way to do this?
For Reference:
- I am using I am using this package: https://github.com/felixge/node-mysql
UPDATE/ANSWER
Based on EternalHour 's answer, the correct syntax would be:
var newStr = req.body.firstName + "%"
var sql = "SELECT cols FROM tbl WHERE col LIKE ? ORDER BY key"
sql = mysql.format(sql, newStr)