Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Array of Arrays from DB

by Anonymous Monk
on May 30, 2002 at 19:29 UTC ( [id://170497]=perlquestion: print w/replies, xml ) Need Help??

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

Hello:

I have what seemed like a simple problem at first, but I cannot get my code to work. Basically, I have a simple SQL SELECT statement (which returns only 3 fields) I am performing on a MySQL database using DBI and DBD::mysql. I want to do a fetchrow_array, then take each returned row and push it into a multidimensional array. What it looks like the code below gets me is an array of arrays with the correct number of elements from the SELECT statement, but the @drivers array I am pushing into contains the arrays with no data. To make sure I am getting the data out of the database properly, I can print the @arr and return the expected data. Am I missing something obvious here, or am I just going about this all wrong? Is there a better way to return db results into an array of arrays?

Thanks, and btw, this is by far the most helpful perl resource on the web.
# build multidimensional array from results while (@arr = $sel->fetchrow_array) { push (@drivers, \@arr); # prints the correct data from the db print "arr: @arr\n"; } # prints the right number of ref's print @drivers; # this just prints the commas and the spaces foreach my $item (@drivers) { print "$item->[0], $item->[1], $item->[2]"; }

Replies are listed 'Best First'.
•Re: Array of Arrays from DB
by merlyn (Sage) on May 30, 2002 at 19:35 UTC
      Great article, that is exactly what I needed to know.

      Thanks
Re: Array of Arrays from DB
by abaxaba (Hermit) on May 30, 2002 at 20:40 UTC
    Why mess with the push at all?
    my $rows = $sel->fetchall_arrayref(); # still prints the right number of refs print @$rows; foreach my $row (@$rows) { print join (",", @$row) }

    ÅßÅ×ÅßÅ
    "It is a very mixed blessing to be brought back from the dead." -- Kurt Vonnegut
Re: Array of Arrays from DB
by fenonn (Chaplain) on May 30, 2002 at 20:43 UTC
    Look at something like this. It will fetch all the rows ( assuming no errors ) and put them in a reference to an array of arrays.
    my $sth = $dbh->prepare( 'SELECT * FROM tbl'); $sth->execute() my $arrayRef = $sth->fetchall_arrayref([]);

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (1)
As of 2024-04-24 15:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found