2

I am fetching values from web service. And I have to insert those values into the table in Web SQL database.

I have 4 records. I have inserted the following code into the loop, but only the last record is added in database and not the first 3 records.

for(var t=0;t<main_category.length;t++){
        db.transaction(function(tx){
            var insertStatement="INSERT INTO main_menu(catId,catName,catImage) VALUES(?,?,?)";
            tx.executeSql(insertStatement, [menu_id, menu_name, menu_img]);
            console.log("values inserted "+ t);
        });
}

I tried many solutions, following link has one of them,

Web SQL Database + Javascript loop

But, it did not work. Please suggest me how can I populate the table with dynamic values.

Community
  • 1
  • 1
Deepika
  • 331
  • 2
  • 7
  • 20

1 Answers1

2

try this:

for(var t = 0; t < main_category.length; t++){
        (function(i) {
            var item = main_category[i];
            var menu_id = item.id, menu_name = item.name, menu_img = item.img;
            db.transaction(function(tx) {
                var insertStatement="INSERT INTO main_menu(catId,catName,catImage) VALUES(?,?,?)";
                tx.executeSql(insertStatement, [menu_id, menu_name, menu_img]);
                console.log("values inserted "+ i);
            });
        })(t);
}

result:

ssut
  • 431
  • 2
  • 8
  • but the values are not getting inserted in the table in database. – Deepika Jul 08 '14 at 06:30
  • i am working this code.. http://puu.sh/a1Lds/d72bb5e8d3.png , so which browser are you using? – ssut Jul 08 '14 at 06:34
  • Aah! made slight changes, its working just the catNames and catImages are having issues, all values are getting inserted there in first row then decrement by 1 in second row and so on. – Deepika Jul 08 '14 at 06:34