mysqlnode.jsnode-mysql

node.js-MySQL COUNT the number of records


I have following code.

var mysql = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'test'
});
connection.connect();

var userdata = '24';

var sql = 'SELECT COUNT(*) FROM names WHERE age = ?'
connection.query(sql, [userdata], function(err, rows, fields) {
  if (err) throw err;
  console.log('Query result: ', rows);
});

connection.end();

I want to get the total number of records from table 'names' where 'age' = 24. I receive the following on my node.js command prompt.

Query result:  [ { 'COUNT(*)': '14' } ]

My question is how to store this number 14 in a variable for further use.

I know I can do this just by changing the 'sql' line to

var sql = 'SELECT * FROM names WHERE age = ?'

and then console line to

console.log('Query result: ', rows.length);

But still is there another way?


Solution

  • Rewrite the

    var sql = 'SELECT COUNT(*) FROM names WHERE age = ?'
    

    To look like, i.e.:

    var sql = 'SELECT COUNT(*) AS namesCount FROM names WHERE age = ?'
    

    Then, you will get Query result: [ { 'namesCount': '14' } ].

    so now you have

    rows[0].namesCount
    

    Good enough?