How to make a query with Node.js and Mysql

Asked

Viewed 1,574 times

4

Hello, I’m starting with Node.js and MySQL, and I have some problems at the moment. Well, I have a table called users, and I need to request data for verification, for example: My site has a registration form, but you need 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 variable emailCadastro comes from the user’s form.

The interpreter returns the following error:

Cannot read property 'email' of undefined

I wonder what the mistake is here and if anyone could help me.

  • Your database is actually called "table"?

  • No. Why? It doesn’t affect the right question?

  • It depends, if the problem is a basis that doesn’t exist, it affects.

  • Well the table exists

1 answer

0


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

If what you need is to pass the email to the query then you should concatenate it with + which is the concatenation symbol in Javascript. I suggest you change the code as I put it below (eventually you may have to take the quotes around that 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) {
  • still returns "Undefined"

  • @Perrytheplatypus what gives console.log(email) before the connection?

  • 1

    Undefined . I don’t think you’re getting the form data. I’ll check

  • I think the problem is in the data loop, which I’m unable to perform. In php for example you use a while and mysql_fetch_array, what would that function be in mysql Node?

  • @Perrytheplatypus in Node a callback gives all the results at once. If you need to iterate you can do .forEach. But if the email gives Undefined you have to add the code from where you get it emailCadastro to see what’s going on there.

  • 1

    thank you, that’s right

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.