Mark
Mark

Reputation: 1852

Retrieving database rows as a hashmap

I'm new to Perl (mainly PHP background), and wondering if I can retrive database rows using DBI in a similar ouptut as PHP does. This is an array containing hashes, with the hash name as the database column names. i.e. something like:

[0] -> {
    'firstname' -> 'mark',
    'surname' -> 'smith'
},
[1] -> {
    'firstname' -> 'fred',
    'surname' -> 'baker'
},
....

I've tried:

    my $ref = $stmt_datahub->fetchall_arrayref;
    print(Dumper($ref));

But this doesn't name the columns. i.e. it returns:

['mark', 'smith'], ['fred', 'baker']

etc.

And fetchall_hashref looks like you need to supply a primary key for it to index the hashes on, which I don't always have, so I'd rather it just output an array.

Is this possible?!

Upvotes: 2

Views: 124

Answers (1)

plusplus
plusplus

Reputation: 2030

You need fetchall_arrayref, but with an argument. This returns an arrayref of hashrefs:

my $results_arrayref = $dbh->fetchall_arrayref( {} );

You can also choose to include only certain columns in the hashref - see the documentation for more details:

https://metacpan.org/module/DBI#fetchall_arrayref

For clarity you probably want to write that data structure in a more Perl-like manner - you wouldn't include the array indices (0, 1, etc) when documenting a Perl list/array/arrayref (PHP muddles the matter a little with its associative arrays)

[ {
   firstname => 'mark',
   surname   => 'smith',
  },
  {
   firstname => 'fred',
   surname   => 'baker',
  },
  ...
],

Upvotes: 3

Related Questions