alex tix
alex tix

Reputation: 165

How to obtain the value of the result in a `node-mysql` query

I am weighting a node.js application, the result I get from my mysql query is,

[ RowDataPacket { name: 'ubuntu' } ]

(Ubuntu is the only thing in the row)

What I would like to do is shorten my variable, "results" so that it equals ubuntu for example, or just every thing between the '', I am new to JS. I am using the standard way of querying the sql database, It is being done as so:

   var mysql      = require('mysql');
   var connection = mysql.createConnection({
   host     : 'localhost',
   user     : 'root', //just using root for my personal testing.
   password : 'root',
   database : 'Sonic'
   });

   connection.connect();

    var connect = connection.query( 'SELECT name FROM Sonic_url',      
       function(err,     fields, results, rows) {
    // if (results === input) {
    var sqldata = results.substring(1, 4);
    console.log(results);
    if (err) throw err;


   //  console.log('I belive we have found what you are after, is: ' +  input + ' ' + 'what you are after?');
   //}
    });

I would like to be able to do a basic IF with the variable input and a variable from the mysql query, so I can print to screen if the result was found or not.

Upvotes: 4

Views: 3632

Answers (1)

gnerkus
gnerkus

Reputation: 12037

The correct signature for the mysql query is:

connection.query(query, function (error, results, fields) {
  // error will be an Error if one occurred during the query
  // results will contain the results of the query
  // fields will contain information about the returned results fields (if any)
});

What you want is to log the value of name. If your query produces one result, you can access this value from the first item in the rows array:

connection.query('SELECT name FROM Sonic_url', function(err, rows, fields) {
  console.log(rows[0].name);
});

Upvotes: 1

Related Questions