#!/usr/bin/perl
use DBI;
use CGI ':standard';
use Template;
BEGIN{
use CGI::Carp qw(fatalsToBrowser carpout);
}
my @myarray,$error_msg;
my $db=DBI->connect('DBI:mysql:sample_db;user=root');
my $num = 5; # items number per page
my $page = param('page') || 1;
my $sth=$db->prepare("select count(*) as dd from test");
$sth->execute;
my ($count) = $sth->fetchrow_array;
if ($count == 0) {
print header(-type=>'text/html',-charset=>'gb2312');
print p("当前没有记录");
$db->disconnect;
exit;
}
my $total;
if ($count % $num ) {
$total = int ($count/$num) +1;
} else {
$total = $count/$num;
}
if ($page < 1 or $page > $total or $page =~ /[^0-9]/) {
print header(-type=>'text/html',-charset=>'gb2312');
print p("页码错误");
$db->disconnect;
exit;
}
my $prepg = ($page -1) || 1;
my $nextpg = ($page +1 > $total) ? $total : $page +1;
my $offset = $num * ($page -1);
$sth=$db->prepare("select id,user,info from test order by id desc limit $offset,$num")
or die "Can't prepare sql statement".DBI->errstr;
$sth->execute();
if($sth->rows==0){
print "No date";
exit;
}
while(my @val=$sth->fetchrow_array()){
push @myarray, {"id"=>$val[0], "user" => $val[1], "info" => $val[2] };
}
$sth->finish();
$db->disconnect();
my $config = {
INCLUDE_PATH => 'ttdir',
};
my $vars = {
path_add => "index.cgi",
Message => \@myarray,
path_page => 'view.cgi',
current_page => $page,
total_page => $total,
pre_page => $prepg,
next_page => $nextpg,
count => $count,
};
my $input = 'view.tt';
my $tt = Template->new($config)||die "$Template::ERROR\n";
print header(-type=>'text/html',-charset=>'gb2312');
$tt->process($input,$vars) || die $tt->error(), "\n";
|