Search code examples
mysqlnode.jsnode-mysql

Escaping query values in MySQL Query (node-mysql)


I am trying to use node-mysql Escaping query values but when I try and insert it into my MySQL query I am getting errors and can't seem to find the problem. I have tried laying out the code in different ways as well, like the one seen in github example I linked.

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 'don\\'t spam!''' at line 1

banReason = Don't spam!

var banr = con.escape(banReason)

let sql
sql = `INSERT INTO modlog (senderid, victimid, duration, releasedate, reason) VALUES ('${message.author.id}', '${user}', '${timeCode}', '${moment().add(timeValue, timeType)}', '${banr}'`
con.query(sql)

Solution

  • To answer the question the correct method is to use ? that can be seen on the node-mysql GitHub Fixed code:

    var values = {senderid: message.author.id, victimid: user, duration: timeCode, releasedate: releaseDate, reason: banReason} 
    con.query('INSERT INTO modlog SET ?', values, function(err, result) {})
    

    See example from referenced answere