prince26121991 has asked for the wisdom of the Perl Monks concerning the following question:

#!C:\perl\bin\perl.exe -w use DBI; use CGI; use HTML::Template; my $cgi = CGI->new; my $dbh = DBI->connect('dbi:mysql:perltest', 'root'); my $t = HTML::Template->new(filename => 'db.tmpl'); $rows = $dbh->selectall_hashref('select id, name, price from products' +,{ Slice => {} } ); foreach my $row (@$rows) { my $id = $row->{id}; my $name = $row->{name}; my $price = $row->{price}; } $dbh->disconnect; print $cgi->header; print $t->output;
Getting error in this code! i.e. Not an ARRAY refrence at C:/Perl/Site/lib/DBI.pm line 2086

P.S.-Please Answer in simple language Because I am just beginner

Replies are listed 'Best First'.
Re: Not An Array reference
by LanX (Saint) on Nov 15, 2013 at 20:48 UTC
    From the DBI docs

    $hash_ref = $dbh->selectall_hashref($statement, $key_field);

    > > The $key_field parameter defines which column, or columns, are used as keys in the returned hash. It can either be the name of a single field, or a reference to an array containing multiple field names. Using multiple names yields a tree of nested hashes.

    I think you either want to pass “Slice“ or [“Slice“]

    Cheers Rolf

    ( addicted to the Perl Programming Language)

Re: Not An Array reference
by tangent (Parson) on Nov 15, 2013 at 21:55 UTC
    selectall_hashref() returns a hash reference not an array reference, and the value of each key is itself a hash reference, so you should access it like this:
    while ( my ($key,$value) = each %$rows ) { my $name = $value->{name}; # ... }
    The second argument to selectall_hashref() should be a column name (or number) or an array reference of column identifiers. Your code passes a hash reference { Slice => {} }. From what I can make out from the docs, the identifier given in the second argument needs to match a column in the statement (the first argument), so if there really is a column called 'Slice' in your database then it should be included in the statement. I would guess that is not the case so this is probably what you want:
    my $hash_ref = $dbh->selectall_hashref('select id, name, price from pr +oducts', 'id' ); while ( my ($id,$value) = each %$hash_ref ) { my $name = $value->{name}; my $price = $value->{price}; # ... }