mysqljs / sqlstring

Simple SQL escape and format for MySQL
MIT License
403 stars 78 forks source link

If the search word includes `%`... #65

Closed kmvan closed 3 years ago

kmvan commented 3 years ago
const { format, escape } = require('sqlstring')
const searchWord = 'word%' // Only want to search end of like "abcword%".
const sql = format(
  `
SELECT * FROM ?? WHERE ?? LIKE ?
`,
  ['table', 'content', `%${escape(searchWord)}`]
)
console.log(sql)
// SELECT * FROM `table` WHERE `content` LIKE '%\'word%\''

Expected output

// SELECT * FROMtableWHEREcontentLIKE '%word\%'

Actual output

// SELECT * FROMtableWHEREcontentLIKE '%\'word%\''

Any idea?

dougwilson commented 3 years ago

Escape function only escapes a value into a sql value. You need to escape the various characters used in LIKE if you don't want them to be special just like with REGEXP.

kmvan commented 3 years ago

If the search word includes ? question mark...

dougwilson commented 3 years ago

I'm not sure what your comment means. The LIKE statement does not assign any special meaning to a question mark, only percent signs and underscores.