HTML::TemplateとDBIでテーブル表示
★選択したフィールドを表示する
用意するファイル
[root@ha-01 HTML]# tree . |-- sample_ht.pl `-- template.tmpl 0 directories, 2 files [root@ha-01 HTML]#
sample_ht.pl
#!/usr/bin/perl use strict; use warnings; use DBI; use HTML::Template; my $hostname = "localhost"; my $user = "user1"; my $passwd = "abcd1234"; my $databse = "db1"; my $tmpl_file = './template.tmpl'; my $template = new HTML::Template(filename => $tmpl_file); my $dsn = "dbi:mysql:database=$databse;host=$hostname;mysql_read_default_file=/etc/my.cnf"; my $dbh = DBI->connect($dsn,$user,$passwd, { 'RaiseError' =>1, 'PrintError' => 0}); my $sth = $dbh->prepare("SELECT postal_code, prefecture,city,town FROM tokyo_postal_code") or die $DBI::errstr; $sth->execute() or die $DBI::errstr; my @array; while (my @row = $sth->fetchrow_array) { push(@array,\@row); } my @table; foreach my $column (@array) { my %hash = ( postal_code => $column->[0], prefecture => $column->[1], city => $column->[2], town => $column->[3] ); push (@table, \%hash); } $dbh->disconnect; print "Content-type: text/html\n\n"; $template->param(postal => \@table); print $template->output;
template.tmpl
<table BORDER="1" > <TMPL_LOOP NAME=postal> <td><TMPL_VAR NAME=postal_code> </td> <td><TMPL_VAR NAME=prefecture> </td> <td><TMPL_VAR NAME=city></td> <td><TMPL_VAR NAME=town></td> </tr> </TMPL_LOOP> </talbe>