Gossamer Forum
Home : General : Perl Programming :

Re: [SimonTOZ] simple Database count

Quote Reply
Re: [SimonTOZ] simple Database count In reply to
Hi SimonTOZ,

You're correct, you would need a second query to get the total number of records. Here is what I would do:

Code:
#!/usr/bin/perl

use strict;
use warnings;
use DBI;
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use HTML::Template;

my $query = CGI->new();

## Define your username/password/SQL server
my $db_server = "localhost";
my $db_user = "videodb";
my $db_password = "password";
my $db_database = "VideoDB";

my $dbh = DBI->connect("dbi:mysql:$db_database:$db_server",
$db_user,$db_password) or die $DBI::errstr;

## Create your SQL call

# Query 1 to get desired records for your loop
my $last_five = q~SELECT imdbID, title, Mediatype, created
FROM videodata
WHERE Mediatype <> '50'
ORDER BY created DESC LIMIT 5~;


# Query 2 to get the total records in DB
my $total = q~SELECT COUNT(*) FROM videodata~;

## Define Template
my $tmpl = HTML::Template->new( filename => "sig.tmpl");

## Feed the information you got from the query (@rows) into your template
$tmpl->param(rows => $dbh->selectall_arrayref($last_five, { Slice => {} }),
count => ($dbh->selectrow_array($total))[0]);

## Print the template
print $tmpl->output;

The selectall_arrayref method called with an empty slice attribute works awesome with HTML::Template for creating your loops.

Hopefully you can catch what I did by reading over the code because I'm a bit too tired right now to explain :) If not just let me know what doesn't make sense.

~Charlie
Subject Author Views Date
Thread simple Database count SimonTOZ 5318 May 1, 2004, 5:17 AM
Thread Re: [SimonTOZ] simple Database count
Chaz 5177 May 13, 2004, 9:33 PM
Thread Re: [Chaz] simple Database count
SimonTOZ 5196 May 13, 2004, 11:05 PM
Thread Re: [SimonTOZ] simple Database count
Chaz 5169 May 14, 2004, 8:33 AM
Post Re: [Chaz] simple Database count
SimonTOZ 5145 May 14, 2004, 7:14 PM