On Fri, 30 Nov 2001, Craig Sharp <[EMAIL PROTECTED]> wrote,

> I need to create a script that will use DBI to retreive information from Informix 
>and then present the information in a table in html.
> 
> The DBI part I have with no problem.  
> 
> I need to use perl to create a table in html that will expand or reduce
> as needed depending on how many rows are retreived from the database.
> In other words, I need the table to be dynamic and add or remove table
> rows for each data row retreived.
> 
> Can anyone provide an example of how to do this or point me in the right
> direction.

There are some ways.  But first, I assume, as you state, you know how to
use DBI and particularly the fetch* family methods.  But I'll use just
fetch() here.

Using HTML feature from CGI.pm

    print
        start_table({-width=>'100%', border=>1), # open the table
        tr([th(['No', 'First Name', 'Last Name'])]); # table header
    my $no = 0;
    # each record contains two columns: firstname and lastname
    while (my $row = $sth->fetch) {
        print tr([td([++$no, $row->[0], $row->[1]])]);
    }
    print end_table();

The advantage is you manage all things from one place.  But this's not for
last.  You'll know later when your script is getting bigger and handling
more complicated HTML.


Using HTML::Template

Prepare a template file contains the layout of the table.

-------table.html-----------------
<table width="100%" border=1>
 <tr>
  <th>No</th>
  <th>First Name</th>
  <th>Last Name</th>
 </tr>
 <TMPL_LOOP listname>
 <tr>
  <td><TMPL_VAR recno></td>
  <td><TMPL_VAR firstname></td>
  <td><TMPL_VAR lastname></td>
 </tr>
 </TMPL_LOOP>
</table>
-----------------------------------

And now the script.  This is a simple example how to use H::T.  More
information is in the module documentation.  It's not part of standard
distribution as CGI.pm, you can download it from CPAN.

    my $page = HTML::Template->new(filename => 'table.html');
    my(@record_rows, $recno);

    while (my $row = $sth->fetch) {
        push @record_rows, {
            recno => ++$recno,
            firstname => $row->[0],
            lastname => $row->[1],
        };
    }

    $page->param(listname => \@record_rows);
    print $page->output;

The advantage using H::T is that you can change the appearance of your
output later without touching the script.  You truly separate HTML (the
information appearance) and Perl (that manages the information itself).


hth
san
-- 
Trabas - http://www.trabas.com



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to