How to escape mysql special characters with sockets.io/node.js/javascript

前端 未结 1 811
遥遥无期
遥遥无期 2020-12-07 04:02

I am using sockets.io to insert user-generated messages into MySQL, but I\'m running into issues inserting records with an apostrophe. I\'ve been trying to use the replace()

相关标签:
1条回答
  • 2020-12-07 04:27

    Don't do it

    You are asking about the wrong solution to the problem.

    To replace the apostrophes with backslash-apostrophes you might use:

    str = msg.replace(/'/g, '\\\'');
    

    but you should not do that. I am only providing that info because that's what your question asks about but read below.

    Why it's a bad idea

    You shouldn't do it on the client side and you shouldn't do in on the server side either. If avoiding SQL injection vulnerabilities was a simple matter of replacing apostrophes with backslash-apostrophes then it wouldn't be an issue. Unfortunately it's more complicated.

    Having the info that you provided it's even impossible to tell whether backslash-apostrophe would even do what you expect in the first place without seeing your code that actually makes the database queries. But it doesn't matter because you should never ever do that. Never. See those answers to see why - those questions are not about SQL injections but the code examples included SQL injection vulnerabilities and the answers explain it:

    • cannot use backtick when using nodejs 7.3.0
    • Node js - Promise Rejection Warning when process a lot of data
    • Is it possible to listen for object instantiation in Node.js?

    Obligatory comic strip

    What you should do instead

    That having been said, you didn't tell what module you're using to query the database but no matter if you're using the mysql module or Sequelize or anything worth its salt, there should always be a mechanism of interpolating variables in a safe manner without manually escaping and concatenating the strings.

    Examples

    You didn't show even a single line of code that is relevant here so I cannot tell you how to fix it but consider this example:

    Unsafe:

    connection.query(
      "SELECT * FROM player WHERE nick = '"
      + data.login + "' AND pass = '" + data.pass + "'",
      function (err, rows) {
        //...
      }
    );
    

    Still unsafe, complex, unreadable, unmaintainable and unreliable:

    connection.query(
      "SELECT * FROM player WHERE nick = '"
      + data.login.replace(/'/g, '\\\'') + "' AND pass = '" + data.pass.replace(/'/g, '\\\'') + "'",
      function (err, rows) {
        //...
      }
    );
    

    Safe and simple:

    connection.query(
      "SELECT * FROM player WHERE nick = ? AND pass = ?", [data.login, data.pass],
      function (err, rows) {
        // ...
      }
    );
    

    More info

    For more info see the docs:

    • https://www.npmjs.com/package/mysql
    • http://docs.sequelizejs.com/en/v3/
    0 讨论(0)
提交回复
热议问题