perl - Using selectall_hashref as I would selectall_arrayref -


i'm doing exercises increase perl skills , 1 of them involves connecting sql database, running query, , returning results array. have far:

my $search = $_[0]; our $dbh = dbi->connect{"dbi:mysql:dbname=database", "root", "password")     or die $dbi::errstr; $sql = $dbh->selectall_arrayref("select player players_sport sport '$search'")     or die $dbi::errstr; @array = map { $_->[0] } @$sql; $dbh->disconnect     or warn "disconnection failed: $dbi::errstr\n"; return @array; 

my next step change code return results hash instead of array, i'm not how proceed. expect use selectall_hashref, online examples i've found use while. want return results, create hash separate steps.

using selectall_hashref method combines prepare, execute , fetchall_arrayref single call. returns reference array containing reference hash each row of data fetched. addon previous comments of responses.

a verbose way of turning selectall_arrayref call in similar hash id primary key, this.

my %rows = (); $i ( 0..$#{$sql} ) {   ($id, $player, $sport) = @{$sql->[$i]};   $rows{$id} = [ $player, $sport ];   } 

and access them:

foreach ( sort(keys(%rows)) ) {    print "$_, -> $rows{$_}->[0], -> $rows{$_}->[1]\n"; } 

now using selectall_hashref, call this. id primary key here.

my $href = $dbh->selectall_hashref( q/select id, player, sport                                        players_sport/, q/id/ ); 

to access keys can use in many ways, here example:

foreach ( keys %$href ) {    print "$_, $href->{$_}->{player}, $href->{$_}->{sport}\n"; } 

your primary key placed $_, individual keys can access out of hash saying.

$href->{$_}->{player} 

again saying:

foreach $i ( keys %$href ) {    print "$i, $href->{$i}->{player}, $href->{$i}->{sport}\n"; } 

each item looping through $i


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -