Samuel Donadelli
Samuel Donadelli

Reputation: 347

How to link three distinct arrays (same size of elements) into a sql table?

I have three arrays with nine elements each one:

@day (1,1,1,2,2,2,3,3,3)

@product (banana, apple, pear, orange, cherry, strawberry, blueberry, yogurt, lettuce)

@total (22,44,67,34,76,44,67,45,86)

I will insert each of these elements in a table:

my $insert_products = $dbh_ref->prepare(q{insert into products_total(day,product,total) values(?,?,?)});

I tried to use the following command:

foreach my $day (@day) {

     foreach my $product (@product) {

         foreach my $total (@total) {

   $insert_products_total->execute($day,$domain,$domain_count);  
                                    }
                                    }
                        }

This foreach creates a massive amount of rows. That is not my goal. My intention is to produce a simple table like this:

day  product    total
1    banana     22
1    apple      44
1    pear       67
2    orange     34
2    cherry     76
2    strawberry 44
3    blueberry  67
3    yogurt     45
3    lettuce    86

Any help in this matter is appreciated,

Upvotes: 0

Views: 33

Answers (1)

Ron Bergin
Ron Bergin

Reputation: 1068

my @day     = (1,1,1,2,2,2,3,3,3);
my @product = qw(banana apple pear orange cherry strawberry blueberry yogurt lettuce);
my @total   = (22,44,67,34,76,44,67,45,86);
my $cnt     = @day - 1;

for my $i (0..$cnt) {
    $insert_products_total->execute($day[$i], $product[$i], $total[$i]);
}

Upvotes: 2

Related Questions