m2j
m2j

Reputation: 1160

node mysql insert and select count not working

i'm using two function function1, function2 consequetivly in node.js.

function1 using to insert the data into the table.

for(var j=0; j < length; j++){

   connection.query('INSERT INTO TestTable SET ?', { row_name : name }, function(err, res){
      if(err) throw err;
   });
}

function2 using to select the count of inserted name, count.

connection.query('select row_name, count(*) as count from TestTable where row_name = ?', name , function (err, rows){  
    console.log(rows);
}); 

where my log gives me name : null, count : 0

what i'm doing wrong?

Upvotes: 0

Views: 532

Answers (1)

Alexandr Lazarev
Alexandr Lazarev

Reputation: 12882

First of all, running mysql queries in a loop is a bad practice. Second, you miss the basics of the asynchronous flow in javascript. Here is a good article where the the basic concepts of asynchronous programming in JavaScript are explained. connection.query is asynchronous, so if you want your code to work, you should run counting query in the callback of the insert query on last iteration.

But as I already mentioned, it is a bad practice to run them in a loop. I would advice you only to build query string in a loop for multiple inserts, but run it only once in the end (with a counting query in the callback).

Upvotes: 1

Related Questions