Search code examples
mysqlnode.jsprepared-statementsql-like

How can I use LIKE in MySQL without removing sanitization?


I'm using the mysql2 package to run my SQL queries and I'm trying to use the LIKE syntax. My issue is that I need to add %% around the variable, but I can't do that since when I inject the variable it injects with SQL injection proof, therefore won't work. The only way I found to do it is putting the variable directly into the query (can be SQL injected to). I even tried wrapping the string with %% but would work either.

WITH SQL INJECTION PROTECTION (WONT RETURN ANYTHING):
await database.execute('SELECT * FROM products WHERE title LIKE %?%', [req.body.query]);

WITHOUT SQL INJECTION PROTECTION (RETURNS):
await database.execute(`SELECT * FROM products WHERE title LIKE %${req.body.query}%`);

Solution

  • Actually, the correct way to do this is to bind the wildcard string to a bare ? placeholder:

    var query = 'SELECT * FROM products WHERE title LIKE ?';
    await database.execute(query, ['%' + req.body.query + '%']);