CREATE TABLE `perl_articles` (
`id` INT(255) NOT NULL AUTO_INCREMENT,
`title` VARCHAR(255) NOT NULL,
`content` TEXT NOT NULL,
PRIMARY KEY(`id`)
);
INSERT INTO `perl_articles`(`title`,`content`) VALUES(`test article 1`, `this is some test content...`);
INSERT INTO `perl_articles`(`title`,`content`) VALUES(`test article 2`, `this is some more test content...`);
INSERT INTO `perl_articles`(`title`,`content`) VALUES(`test article 3`, `this is yet again, some more test content...`);
Okay good, now we can get to the good stuff, the perl code. We will just do a simple loop through all the records in the database to show all the "perl_articles".
#!/usr/bin/perl -wT
use CGI qw(:standard);
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
use Mysql;
# Print content headers and opening HTML tags
print header;
print start_html("Articles");
# Connect to the database and query information
$db = Mysql->connect("localhost", "database", "username", "password");
$query = $db->query("SELECT * FROM perl_articles");
# Check if there are actually any news articles
if ($query->numrows > 0) {
# Loop through all the results or records in the database
while (%result = $query->fetchhash) {
printf "<p>ID: %s<br/>", $result{'id'};
printf "Title: %s<br/>", $result{'title'};
printf "Content:<br/>%s</p>", $result{'content'};
}
} else {
# If there arent any articles in the database
print "<p>Sorry, but no articles currently exist.</p>";
}
# Close HTML tags and finish up
print end_html;
The comments should be self explanitory. If you want to see a working version, you can at the link below. Hope you found this tutorial helpful.
Demo: http://www.dx-h.uni.cc/cgi-bin/listarticles.pl
-maddog39