Reputation: 16771
In Perl I'm making an SQL query akin to the following:
SELECT `id`, `title`, `price` FROM `gamelist`
What I wish to do is take the result of this query and dump it into a hash table. I am using DBI and currently I only know how to do the following:
my %results;
my $count = 0;
while( @result = $statement->fetchrow() ){
%results{'id'}[$count] = $result[0];
%results{'title'}[$count] = $result[1];
%results{'price'}[$count] = $result[2];
$count++;
}
However I don't like using $result[0]
and trusting that the first field will be the ID. I would much rather have something like:
my %results;
my $count = 0;
while( %result = $statement->fetchrow_as_hashtable() ){
%results{'id'}[$count] = %result{'id'};
%results{'title'}[$count] = %result{'title'};
%results{'price'}[$count] = %result{'price'};
$count++;
}
I tried looking around on Google but couldn't find many good answers built into DBI/Perl. I did find an open-source class that offered this functionality, but I feel like this should be possible without the use of someone else's class.
Upvotes: 4
Views: 9131
Reputation: 326
while (my $result = $statement->fetchrow_hashref) {
print $result->{id};
print $result->{title};
print $result->{price};
}
Use fetchrow_hashref to have the result directly in a hash
Upvotes: 5
Reputation: 52029
Consult the DBI
documentation for this use of selectall_arrayref
:
$rows = $dbh->selectall_arrayref($query, {Slice=>{}}, @params)
$rows
is an Array of Hashes.
Upvotes: 4