How to make a query with Node.js and MySQL

4

Hello, I'm starting with Node.js and MySQL , and I have some problems right now. Well, I have a table called users, and I need to make the data request for verification, for example: My site has a registration form, but it needs to check the data to see if there is a user already registered with the same data.

My code is like this so far:

 var pool  = mysql.createPool({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database:'tabela'
});

pool.getConnection(function(err, connection) {
  // Use the connection
  var email = emailCadastro;
  connection.query( 'SELECT * FROM usuarios WHERE email = ?',[email], function(err, rows) {
    // And done with the connection.
    connection.release();

    // Don't use the connection here, it has been returned to the pool.
    console.log(rows[0].email);
  });
});

Please correct me if this code is wrong. The emailCadastro variable comes from the user form.

The interpreter returns the following error:

Cannot read property 'email' of undefined

I would like to know what the error is here and if anyone could help me.

    
asked by anonymous 11.05.2015 / 03:22

1 answer

0

Following the node-mysql documentation this method only accepts 2 arguments . The query and the callback.

If you need to pass the email to the query then you must concatenate it with + which is the concatenation symbol in JavaScript. I suggest you change the code as I put it below (you may have to get the quotation marks around this string with the mail):

pool.getConnection(function(err, connection) {
  // Use the connection
  var email = emailCadastro;
  connection.query( 'SELECT * FROM usuarios WHERE email="' + email + '"', function(err, rows) {
    
11.05.2015 / 08:29