Beefy Boxes and Bandwidth Generously Provided by pair Networks vroom
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: DBI and HTML::Template

by Anonymous Monk
on Nov 22, 2001 at 03:41 UTC ( [id://126939]=note: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.


in reply to DBI and HTML::Template

HTML::Template->param expects an array reference of hash references. So you would need to create a structure like this
$myarrayref = [ { NAME => 'Bob' , JOB => 'Programmer'} , { NAME => 'Bill' , JOB => 'Manager'} , ];
and use it like this.
$template->param( EMPLOYEE_INFO => $myarrayref);
To do this using DBI you would want to do something like the following. First fetch each row as a hash reference then push each one of these onto a array reference. Note: you will need to dereference the array reference hence the @$myarrayref.
# Create statement handle $sth = $dbh->prepare($somesql); # execute statement handle $sth->execute(); # loop through rows while ($hashref = $sth->fethrow_hashref()) { push @$myarrayref , $hashref; } # clean up statement handle $sth->finish();
Once you have the array reference of hash references you can pass this to the param method of HTML::Template like so.
$template->param(EMPLOYEE_INFO => $myarrayref);

Replies are listed 'Best First'.
Re: Re: DBI and HTML::Template
by chipmunk (Parson) on Nov 22, 2001 at 05:04 UTC
    # loop through rows while ($hashref = $sth->fethrow_hashref()) { push @$myarrayref , $hashref; }
    Be aware that the documentation for DBI specifically forbids using fetchrow_hashref in that way:
    Currently, a new hash reference is returned for each row. This will change in the future to return the same hash ref each time, so don't rely on the current behaviour.
    Although your code will work with existing versions of DBI, in some future version it will break with every reference in the array pointing to the same hash, containing the last row fetched. Instead, you should make sure to create a new hash for each row:
    # loop through rows while ($hashref = $sth->fetchrow_hashref()) { push @$myarrayref , { %$hashref }; }
    There's also fetchall_arrayref, as lachoy explained.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://126939]
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.