Hello! First, thanks to you all for your work on DBI. I use it
frequently and find it well put together as well as useful tool.
Attached is a simple patch to the code AND pod of 1.14 which adds the
function 'selectall_hashref', which is just like selectall_arrayref, but
it defaults to returning an array of hashes instead of an array of
arrays. This is extremely useful in some cases. For example, this sort
of construct can be passed directly into an HTML::Template object.
Thanks.
-mark
http://mark.stosberg.com/
--- DBI.pm.org Wed Mar 21 20:22:02 2001
+++ DBI.pm Wed Mar 21 21:20:09 2001
@@ -29,6 +29,7 @@
$rv = $dbh->do($statement, \%attr, @bind_values);
$ary_ref = $dbh->selectall_arrayref($statement);
+ $ary_ref = $dbh->selectall_hashref($statement);
@row_ary = $dbh->selectrow_array($statement);
$ary_ref = $dbh->selectcol_arrayref($statement);
@@ -275,8 +276,9 @@
prepare => { U =>[2,3,'$statement [, \%attr]'] },
prepare_cached => { U =>[2,4,'$statement [, \%attr [, $allow_active ] ]'] },
selectrow_array => { U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'] },
- selectall_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'] },
selectcol_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'] },
+ selectall_hashref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'] },
+ selectall_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'] },
handler => { U =>[2,2,'\&handler'] },
ping => { U =>[1,1] },
disconnect => { U =>[1,1] },
@@ -955,6 +957,16 @@
return $sth->fetchall_arrayref($slice);
}
+ sub selectall_hashref {
+ my ($dbh, $stmt, $attr, @bind) = @_;
+ my $sth = (ref $stmt) ? $stmt
+ : $dbh->prepare($stmt, $attr);
+ return unless $sth;
+ $sth->execute(@bind) || return;
+ my $slice = $attr->{dbi_fetchall_arrayref_attr} ||= {};
+ return $sth->fetchall_arrayref($slice);
+ }
+
sub selectcol_arrayref {
my ($dbh, $stmt, $attr, @bind) = @_;
my $sth = (ref $stmt) ? $stmt
@@ -2236,6 +2248,24 @@
L</RaiseError> is not set, then it will return with whatever data it
has fetched thus far.
+=item C<selectall_hashref>
+
+ $ary_ref = $dbh->selectall_hashref($statement);
+ $ary_ref = $dbh->selectall_hashref($statement, \%attr);
+ $ary_ref = $dbh->selectall_arrayref($statement, \%attr, @bind_values);
+
+This utility method combines L</prepare>, L</execute> and
+L</fetchall_arrayref> into a single call. It returns a reference to an
+array containing a reference to an hash for each row of data fetched.
+
+The C<$statement> parameter can be a previously prepared statement handle,
+in which case the C<prepare> is skipped. This is recommended if the
+statement is going to be executed many times.
+
+If any method except C<fetch> fails, and L</RaiseError> is not set,
+C<selectall_arrayref> will return C<undef>. If C<fetch> fails and
+L</RaiseError> is not set, then it will return with whatever data it
+has fetched thus far.
=item C<selectcol_arrayref>