5.3. Listing stock items

The shell of a stock-listing CGI script is available in your cgi-bin directory as stocklist.cgi.

#!/usr/bin/perl -w
use strict;
use DBI;

my $driver = 'mysql';
my $database = 'trainXX';
my $username = 'trainXX';
my $password = 'your_password_here';

my $dsn = "DBI:$driver:database=$database";
my $dbh = DBI->connect($dsn, $username, $password) || die $DBI::errstr;

my $sql_statement = "select * from stock_item";
my $sth = $dbh->prepare($sql_statement);
$sth->execute() or die ("Can't execute SQL: " . $dbh->errstr());

print <<"END";

Content-type: text/html

<h1>Stock items</h1>
<table border>
<tr>
        <th>ID</th>
        <th>Name</th>
        <th>Price</th>
        <th>Quantity</th>
</tr>
END

while (my @ary = $sth->fetchrow_array()) {
        print <<"END";
<tr>
        <td>$ary[0]</td>
        <td>$ary[1]</td>
        <td>$ary[2]</td>
        <td>$ary[3]</td>
</tr>
END
}

print "</table>\n";

$dbh->disconnect();