0

Hello great Stackoverflow coders,I have tried to escape mysql query in node.js using mysql.escape(),pool.escape() but it returns error mysql or pool is not defined respectively. below is the code

var mysql=require('mysql');
exports.con = mysql.createConnection( {
// db connections goes here
 });


    sql.con.query("INSERT INTO `so_gb`(`user`, `neol`) VALUES ('"+mysql.escape(req.body.urt)+"','"+mysql.escape(req.body.mery)+"')", 
        function(err, user) {
            if(!err)
            {
nackolysis
  • 217
  • 4
  • 13
  • My guess is that you're not loading `mysql` into each file that references it. – robertklep Jul 30 '16 at 18:58
  • `INSERT INTO so_gb (user, neol) VALUES ('"+mysql.escape(req.body.urt)+"','"+mysql.escape(req.body.mery)+` I don't know why but author of mysql-package write dirty example containts same code. More better (safer and cleaner) use placeholders e.g. `'insert into ... values (?, ?)', [arg1, arg2]`. See 3-rd example in section https://github.com/mysqljs/mysql#escaping-query-values – Aikon Mogwai Jul 30 '16 at 19:10

1 Answers1

0

I assume the first 4 lines are in one .js file and the next 4 lines are in another .js file, that being the case you can't expect to refer to the mysql variable defined in the first file from the second file, you can only access the objects you put in the exports object.

You need to change the first file like this:

var mysql=require('mysql');
exports.con = mysql.createConnection(
// db connections goes here
});
exports.escape = mysql.escape;

Adding in that line will make the mysql escape function accessible via the exports object.

And then change the second file like this:

var con = require('firstFile.js');
con.query("INSERT INTO `so_gb`(`user`, `neol`) VALUES ('"+con.escape(req.body.urt)+"','"+con.escape(req.body.mery)+"')", 
    function(err, user) {
        if(!err)
        {

The require statement will give you access to the exports object from the first file. Then you can use con.escape() which will call mysql.escape() in the first file.

You might want to consider reading this answer on the module.export object:
What is the purpose of Node.js module.exports and how do you use it?

Community
  • 1
  • 1
James
  • 361
  • 3
  • 11
  • can i still use mysql.escape() in the code above. it should be var mysql = require('firstFile.js'); – nackolysis Jul 30 '16 at 21:01
  • Yes you can use mysql.escape() if you change the require line to var mysql = require('firstFile.js'); – James Jul 30 '16 at 21:03
  • @nackolysis However, I would consider it poor practice to have two variables named mysql with different functionality - this can lead to confusion later. Rename the one in the first file to mysql_lib or something similar. – James Jul 30 '16 at 21:05