nodejs, get value from a mysql SELECT

4

Well, I wanted to know, how can I get this result, and turn it into variable and be able to use functions inside the script, example take that Name warrior and use it as a variable, type:

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

How can I do var username = mysql.Name; ?

    
asked by anonymous 05.06.2017 / 11:17

1 answer

5

This rows variable that the callback gives you is a collection, type array. Then to use you need to access via index.

If you only have one suffice:

var user = rows[0];

and then access properties, such as console.log(user.Name); ;

If you are using a recent version of the node you can even use 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);
    }
);
    
05.06.2017 / 11:19