Search code examples
node.jsnode-mysql

Nodejs with Mysql Database


I'm using nodejs with MySQL for the first time , I'm struggling to properly preparing statements ,I have no problems when writing and executing some insertion statements but when i tried to write the selection statements i can't know what is the correct syntax .I can't find tutorial for the beginner This is the selection code

io.sockets.on('connection', function(client) {  
client.on('check_id', function(login_feilds) {

     console.log(login_feilds);

     var login_feilds_as_json = login_feilds ,
      Email = login_feilds_as_json.email ,
      password = login_feilds_as_json.password ;
    var sql = "SELECT * FROM ?? WHERE ?? = ? AND ?? = ?";
     var inserts = ['users', 'email', Email,'password',password];
            sql = mysql.format(sql, inserts);
                 console.log(sql);


  connection.query( sql , function(err, rows){
     if(error){

      console.log(error.message);
    }else{
      console.log('found it'); };

  });

}); 
});

when I run the above code I got this

{ email: 'user@windowslive.com', password: 'user' }
SELECT * FROM `users` WHERE `email` = 'user@windowslive.com' AND `password` =
 'user'

C:\Users\jiil\Desktop\our-project\node_modules\mysql\lib\protocol\Parser.js:82
        throw err;
              ^
ReferenceError: error is not defined

could you help me to figure out what i have to do or give me any good resources' links .


Solution

  • The problem is that you wrongly use variable name in your callback function. You need to change error to err.

    connection.query(sql, function(err, rows){
        if (err) {  
          console.log(err.message);
        } else {
          console.log('found it'); 
        } 
      });
    

    Hope it will be useful for you.