Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: DBI and HTML::Template

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


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 10: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
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2022-08-19 20:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?