Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Building an array of hashes from database

by dbwiz (Curate)
on Sep 26, 2003 at 16:37 UTC ( [id://294485]=note: print w/replies, xml ) Need Help??


in reply to Building an array of hashes from database

First, immediate solution: put my %data =() inside your loop and it should work.

The reason is that you are pushing the same reference over and over. That's why you see always the same record. If you put the hash inside the block, instead, you make a fresh one at each loop.

However, there are several better ways. The one I prefer is this:

my $sth = $dbh->prepare($query); $sth->execute(); my $records = $sth->fetchall_arrayref({}); # notice an empty hashref here ^

For more ways of dealing with hashes, see DBI Recipes in our Tutorials.

Replies are listed 'Best First'.
Re: Re: Building an array of hashes from database
by iburrell (Chaplain) on Sep 26, 2003 at 20:16 UTC
    DBI has a convienence function on the dbh that does the prepare, execute, and fetchall in one call. Getting an arrayref of hashrefs requires a special argument.
    my $records = $dbh->selectall_arrayref($sql, { Slice => {} });

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://294485]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (4)
As of 2024-04-16 14:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found