scriptkiddie
scriptkiddie

Reputation: 605

Node.js : How to use the output of one query to a input of another query

I am new to node.js, I want to input output of a query to another query please help

 pool.getConnection(function(err, connection) {
   connection.query("select * from tbl_chat", function(err, rows) {
       console.log(rows[0]['from_id']);
       var fromid = rows[0]['from_id'];
   });
   console.log(fromid);//throws ReferenceError: fromid is not defined
   console.log(rows[0]['from_id']);// throws ReferenceError: rows is not defined

  //I want to use the fromid in the following query 

   /*connection.query("select * from tbl_chat where from_id=?",[fromid], function(err, rows) {
       console.log(rows[0]['from_id']);
   });*/
 });

Upvotes: 0

Views: 177

Answers (1)

Kevin Grosgojat
Kevin Grosgojat

Reputation: 1379

NodeJs database query are asynchronous, so you have to put your console.log in the callback, or do it with promises.

Try it:

 pool.getConnection(function(err, connection) {
   connection.query("select * from tbl_chat", function(err, rows) {
       console.log(rows[0]['from_id']);
       var fromid = rows[0]['from_id'];
       console.log(fromid);
       console.log(rows[0]['from_id']);
       connection.query("select * from tbl_chat where from_id=?",[fromid], function(err, rows) {
           console.log(rows[0]['from_id']);
       });
   });
 });

Upvotes: 1

Related Questions