On Fri, Feb 27, 2009 at 08:43, David Shere <dsh...@steelerubber.com> wrote:
> The following sub uses "fetchall_arrayref" in the DBI module to put the
> results of an SQL command into an array, where each element of the array
> is a hash of that records name/value pairs.  The documentation says to
> pass it a reference to a hash.  My interpretation of that requirement is
> below.  Did I miss something?
>
> sub SQLCom { # Issues a command to the MySQL database.
>    my $dbh           = shift; # Database object (from DBI)
>    my $CommandString = shift; # SQL Command
>    my $Query         = $dbh->prepare($CommandString);
>
>    $Query->execute() or (print "Can't execute database command
> \"$CommandString\"\n\n" and return undef);
>    if ($CommandString =~ m/SELECT/i) {
>        my @return = @{$Query->fetchall_arrayref(\%asfd)};
>        return @return;
>    }
>    return "true";
> }

Where does %asdf come from?  Anyway, there are four ways to call
fetchall_arrayref.

You can call it with an empty arrayref or not arguments at all:

my $AoA = $sth->fetchall_arrayref([]);
my $AoA = $sth->fetchall_arrayref();

$AoA contains a reference to an array of arrays, so, if the data in
the data base looked like this:

foo|bar|baz
1|2|3
4|5|6
7|8|9

then the $AoA would look like this

my $AoA = [
    [ 1, 2, 3 ],
    [ 4, 5, 6 ],
    [ 7, 8, 9 ],
];

You can call it with an empty hashref:

my $AoH = $sth->fetchall_arrayref({});

$AoH contains a reference to an array of hashes, so, if the data in
the data base looked like this:

foo|bar|baz
1|2|3
4|5|6
7|8|9

then the $AoH would look like this

my $AoH = [
    [ foo => 1, bar => 2, baz => 3 ],
    [ foo => 4, bar => 5, baz => 6 ],
    [ foo => 7, bar => 8, baz => 9 ],
];

You can call it with a hashref of the names columns:

my $AoH = $sth->fetchall_arrayref({foo => 1, baz => 1});

$AoH contains a reference to an array of hashes, so, if the data in
the data base looked like this:

foo|bar|baz
1|2|3
4|5|6
7|8|9

then the $AoH would look like this

my $AoH = [
    [ foo => 1, baz => 3 ],
    [ foo => 4, baz => 6 ],
    [ foo => 7, baz => 9 ],
];


-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to