My program only gets the first value of the array and i need all

im having a problem in my program. i need to pass all the values of my array to the database. Here is my program..

exports.post = function(req, res){
	var obj = {};
	var eacode = req.body.eacode;
	db.all("SELECT * FROM localarea_listings WHERE eacode= ? ",eacode, function(err,rows2){
	rows2.forEach(function (row2) {
	var hcn = row2.hcn;
	var shsn = row2.shsn;
	console.log(hcn);
	console.log(shsn);
	});
	db.all("UPDATE localarea_listings SET INTERVIEW_STATUS = ? WHERE eacode = ? 
        and hcn =? and shsn = ?",[req.body.INTERVIEW_STATUS, req.body.eacode, 
        req.body.hcn, req.body.shsn],function(err,rows){
		if (err)
    {
    console.log("Error Updating : %s ",err );
		}
		else 
    console.log("Success updating localarea_listings");
		});
	});	
};

The data will process depending on the variable eacode from the database localarea_listings.db

Lets say the values hcn is 1,2,3,4,5 and shsn is 6,7,8,9,10 respectively.

when i print hcn and shsn, the value will display what i want, which is hcn=[1,2,3,4,5] and shsn=[6,7,8,9,10]

The problem will starts here, when i update it, it only update the first value of the array which is 1 for hcn and 6 for shsn. i tried using row2[0].hcn and row2[0].shsn but it will cause error..

I hope my question is clear. Thanks!

Answers 1

  • You need to move the update inside the forEach

    exports.post = function(req, res) {
      var obj = {};
      var eacode = req.body.eacode;
      db.all("SELECT * FROM localarea_listings WHERE eacode= ? ", eacode, function(err, rows2) {
          rows2.forEach(function(row2) {
            var hcn = row2.hcn;
            var shsn = row2.shsn;
            console.log(hcn);
            console.log(shsn);
            db.all("UPDATE localarea_listings SET INTERVIEW_STATUS = ? WHERE eacode = ? and hcn = ? and shsn = ? ",[req.body.INTERVIEW_STATUS, req.body.eacode, hcn, shsn], function(err, rows) {
              if (err) {
                console.log("Error Updating : %s ", err);
              } else
                console.log("Success updating localarea_listings");
            });
          });
          
      });
    };


Related Articles