12

im trying to save the result of MySql query in variable using node-mysql model and node.js so i have this code:

connection.query("select * from ROOMS", function(err, rows){
if(err) {
    throw err;
} else {
    console.log(rows);
}
});

and the result is :

[ { idRooms: 1, Room_Name: 'dd' },
  { idRooms: 2, Room_Name: 'sad' } ]

so i need to store this results in variable so i try like this:

 var someVar = connection.query("select * from ROOMS", function(err, rows){
if(err) {
    throw err;
} else {
    return rows;
}
});

console.log(someVar);   

but is not working thanks for any help in advance.

0

4 Answers 4

22

Well @Fadi, connection.query is async, which mean when your call your console.log(someVar), someVar has not been set yet.

What you could do:

var someVar = [];

connection.query("select * from ROOMS", function(err, rows){
  if(err) {
    throw err;
  } else {
    setValue(rows);
  }
});

function setValue(value) {
  someVar = value;
  console.log(someVar);
}
4
  • ok thanks but another question if i don't store the result in varible how can i send it throw socket.io to the cline-side
    – Fadi
    Sep 29, 2014 at 13:00
  • 3
    @Fadi, you should read this article about how to design your solution when building things in node.js. It's not that long and totally worth reading. Sep 29, 2014 at 13:04
  • I am trying to return the someVar variable but get "Promise Pending" message. Any ideas? Dec 19, 2018 at 13:27
  • its console out the data but it can't be sented as response, please help me with this Feb 14 at 16:10
2

You can't do that because network i/o is asynchronous and non-blocking in node.js. So any logic that comes afterwards that must execute only after the query has finished, you must place inside the query's callback. If you have many nested asynchronous operations you may look into using a module such as async to help better organize your asynchronous tasks.

2

As a complement to already given answers.

var **someVar** = connection.query( *sqlQuery*, *callback function( err , row , fields){}* )

console.log(**someVar**);

This construction will return in someVar information of this connection and his SQL query . It will not return values ​​from the query .

Values ​​from the query are located in the callback function ( err , row , fields)

1

Here is your answer if you want to assign a variable to res.render

//before define the values
var tum_render = [];
tum_render.title = "Turan";
tum_render.description = "Turan'ın websitesi";

//left the queries seperatly
var rastgeleQuery = "SELECT baslik,hit FROM icerik ORDER BY RAND() LIMIT 1";
var son5Query = "SELECT baslik,hit FROM icerik LIMIT 5";

var query_arr = [rastgeleQuery, son5Query];
var query_name = ['rastgele', 'son5'];

//and the functions are

//query for db
function runQuery(query_arr,sira){
    connection.query(query_arr[sira], function(err, rows, fields) {
        if (err) throw err;
        var obj = [];
        obj[query_name[sira]] = rows;
        sonuclar.push(obj);
        if (query_arr.length <= sira+1){
            sonuc();
        }else{
            runQuery(query_arr, sira+1);
        }
    });
 }

//the function joins some functions http://stackoverflow.com/questions/2454295/javascript-concatenate-properties-from-multiple-objects-associative-array
function collect() {
      var ret = {};
      var len = arguments.length;
      for (var i=0; i<len; i++) {
        for (p in arguments[i]) {
          if (arguments[i].hasOwnProperty(p)) {
            ret[p] = arguments[i][p];
          }
        }
      }
      return ret;
}

//runQuery callback
function sonuc(){
        for(var x = 0; x<=sonuclar.length-1; x++){
            tum_render = collect(tum_render,sonuclar[x]);
        }
    console.log(tum_render);
    res.render('index', tum_render);
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.