0

I'm trying to run a function in a for loop, the problem is that it takes only the last 'key' from the loop and runs the code for it.

Here's my code:

/*Global variable*/
var PItem = "Item";
for(var key in Prices){
    PItem = key;
    var sql = 'SELECT EXISTS(SELECT * FROM `items` WHERE `name` = "'+PItem+'")';
    con.query(sql , function(err, result){
        if(err) return console.log(err);
        for (var key6 in result){
            for(var key7 in result[key6]) var result2 = result[key6][key7];
        }
        if(result2 == 0){
            var sql = 'INSERT INTO `items` (`name`, `buy`, `sell`, `stock`, `maxStock`) VALUES ("'+PItem+'", '+Prices[PItem].buy+', '+Prices[PItem].sell+', '+Prices[PItem].stock+', '+Prices[PItem].maxstock+')';
            con.query(sql, function(err, result){
                if(err) return console.log(err);
            });
        }
    });
}

It adds to the MySql database several rows with the same values of the last 'key' from the loop.

Nikita Ivanov
  • 505
  • 1
  • 4
  • 18

0 Answers0