-1

i am fetching data from a database...what i would like to achieve is for every data row fetched(id,title) to create a hash ref

{
   id => data->[0],
   title => data[1]
}

and push this hash ref into array ref in order to create the following format

 {  category => [
                   {
                    id => 1,
                    title => "title1"
                   },
                   {
                   id => 2,
                   title => "title2"
                   }
                  ]
              }

what i have made:

   my $productCategories->{category} = [];
    my $product = {};
    my $sth = $dbh->prepare(qq[SELECT id,title FROM ].DB_SCHEMA().qq[.product_categories]) || die $dbh->errstr;
    $sth->execute() || die $dbh->errstr;
    while(my $data = $sth->fetch){
        $product =  {
                    id      =>  $data->[0],
                    title   =>  $data->[1]
                    };
        push $productCategories->{category}, $product;
    }

but it is not working...

1

2 Answers 2

4

Turn on use strict; use warnings; and it'll tell you why.

push on reference is experimental

Not an ARRAY reference

Try:

push @{$productCategories->{category}}, $product;

Also: Be careful with declaring things you're pushing outside the loop - you should be ok in this case, but bear in mind you're pushing a reference. If you re-use variables, you can end up with pushing the same reference.

Sign up to request clarification or add additional context in comments.

3 Comments

Does in my sample. But perhaps you need to be clearer what you mean by 'not working'.
using warn Data::Dumper::Dumper(@{$productCategories->{category}}); i am getting this response: 'id' => 2 }; $VAR3 = { 'title' => 'pizza', 'id' => 3 }; $VAR4 = { 'title' => "\x{396}\x{3c5}\x{3bc}\x{3b1}\x{3c1}\x{3b9}\x{3ba}\x{3ac}", 'id' => 4 };
You need to pass a ref to Data::Dumper. print Dumper $productCategories should do the trick.
4

DBI has many methods for fetching data. One of them is called fetchall_arrayref() and it will give you back the data in exactly the structure that you need - no need to build it up yourself.

my $sth = $dbh->prepare(qq[SELECT id,title FROM ] .
                        DB_SCHEMA() .
                        qq[.product_categories])
  || die $dbh->errstr;

$sth->execute() || die $dbh->errstr;

# Pass a hash ref to get each row back as a hash.
$productCategories->{category} = $sth->fetchall_arrayref({});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.