node.js - node mysql insert and select count not working -
i'm using 2 function function1
, function2
consequetivly in node.js
.
function1
using insert data table.
for(var j=0; j < length; j++){ connection.query('insert testtable set ?', { row_name : name }, function(err, res){ if(err) throw err; }); }
function2
using select count of inserted name, count.
connection.query('select row_name, count(*) count testtable row_name = ?', name , function (err, rows){ console.log(rows); });
where log
gives me name : null, count : 0
what i'm doing wrong?
first of all, running mysql queries in loop bad practice. second, miss basics of asynchronous flow in javascript. here article the basic concepts of asynchronous programming in javascript explained. connection.query
asynchronous, if want code work, should run counting query in callback of insert query on last iteration.
but mentioned, bad practice run them in loop. advice build query string in loop multiple inserts, run once in end (with counting query in callback).
Comments
Post a Comment