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.
What about fetchrow_hashref
?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With