Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to return results from node mysql

How to return results from node mysql

Problem

How to return results from Node Mysql https://github.com/felixge/node-mysql I'm trying to access the results returned outside of the function.

var mysql = require('mysql');
var TEST_DATABASE = 'zenoir';
var TEST_TABLE = 'tbl_sessions';
var client = mysql.createClient({
  user: 'root',
  password: 'secret',
});

var outer = 20;
client.query('USE '+TEST_DATABASE);

client.query(
  'SELECT ses_title FROM '+TEST_TABLE,
  function selectCb(err, results, fields) {
    if (err) {
      throw err;
    }


    var boom  = results;
    var rooms = [];
    var index = 0;
    var name = 'session';

    for(var b in boom){
         rooms[b] = {};
         rooms[b][name + index] = boom[b]['ses_title'];
         index += 1;
    }

    var exe = {};
for(var mon in rooms){
 for(var zeb in rooms[mon]){
    exe[mon] = rooms[mon][zeb];
 }

}


    outer = exe; //I want to access the exe variable outside the function scope

    client.end();
  }
);

console.log(outer); //I still get the initial value 20 in here.
Problem courtesy of: user225269

Solution

Well, as you can see here, query() can be use with those params :

  • SQL query, SQL query param, callback on completion
  • SQL query, callback on completion

You are using the 2nd one.

Callback function is active only when the Query is done (which means, it can take time). Javascript doesn't stop on your query and continue with the script ( console.log(outer); ) and when your query is done then it apply the callback function and change outer.

Solution courtesy of: Shikiryu

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How to return results from node mysql

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×