nodejs, get value from a SELECT mysql

Asked

Viewed 2,136 times

4

IMAGEM DE EXEMPLO

Well, I wanted to know, how can I take this result, and turn into variable and be able to use within functions in the script, example take this Name Warrior and use as if it were a variable, like:

con.query(
  'SELECT * FROM servers WHERE id = ?', [userLandVariable],
  function(err, rows){
    if(err) throw err;
    console.log(rows);
  }            
);

has how I do var username = mysql.Name;?

1 answer

5


This variable rows the callback gives you is a collection, like array. So to use you need to access via index.

If you only have one:

var user = rows[0];

and then access the properties, for example console.log(user.Name);;

If you are using a recent version of Node you can even use unstructuring (destructuring assignment) of the second callback argument:

con.query(
    'SELECT * FROM servers WHERE id = ?', 
    [userLandVariable], 
    function (err, [user]){
        console.log(user.Name);
        chamrOutraFuncao(user.Name);
    }
);
  • Got it, thanks for the help ;D

Browser other questions tagged

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