nackolysis nackolysis - 4 months ago 57
SQL Question

escape mysql query in node.js returns error mysql is not defined

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)
{

Answer

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?