Disclaimer
These instructions/steps worked for me and it may very well work for you on Sun OS / linux distributions. Please note that if you decide to use these instructions on your machine (either for this particular application and/or for other kind of information), you are doing so entirely at your very own discretion and that neither this site, sgowtham.com, nor its author is responsible for any/all damage – intellectual or otherwise.
During the Christmas break of 2005-06 (while I was a graduate student in Michigan Technological University), I thought it would be nice to have a tool to store details pertaining to our research group publications in a MySQL database (instead of a flat HTML file). Some underlying motives were as follows:
- List all publications in a year – helps when generating annual progress reports
- List all publications by any given author(s)
- A combination of the above two possibilities
The server which served our research group website used Sun OS 5.6 and for security-related reasons, it did not have PHP. As such, it became necessary (a good thing!) that this utility had to be written using PERL CGI (Common Gateway Interface). List of required features (implemented over a period of time) included:
- User Side
- Display all publications when no query is submitted (default display) – include a search form
- Searchable by year of publication
- Searchable by two authors
- Searchable by a combination of #2 and #3
- When displaying queried results, include Abstract
- Admin Side:
- Adding a new publication to the database, with PDF upload option (GUI)
- Updating details for an entry that already exists in a database (GUI)
- Deleting an entry from the database (GUI)
- Restricted access
Starting with MySQL database/table structure, these requirements are described one by one in following subsections.
#0. Preliminary Settings
Let us assume that:
- The web documents are stored under /var/www/html and will henceforth be referred to as $DocumentRoot (if you are trying to implement this in your research group in a university/academic institution, please check with your systems administrator for the appropriate value of $DocumentRoot).
- The page (with search form) which users will interact is called publications.cgi and is stored under $DocumentRoot.
- The folder that contains PDF version of publications is called pdf and is located under $DocumentRoot. Make sure this folder has 777 permission.
- The folder that contains administrative CGI scripts is called admin and is located under $DocumentRoot. This folder must have restricted access.
#1. MySQL Database
- Create a database. If einstein is userid of the group’s principal investigator, then einstein_research would be just fine a name for the database.
- Create a dummy user (within MySQL), einstein_webuser, with at least INSERT, UPDATE, SELECT and DELETE previliges on einstein_research database.
- Set a (strong enough) password for this dummy user.
- Create a table within einstein_research database, publications, with following structure:
1 2 3 4 5 6 7 8 9 10 11 12 13
CREATE TABLE `publications` ( `PubID` INT( 11 ) NOT NULL AUTO_INCREMENT , `BibID` VARCHAR( 15 ) DEFAULT NULL , `Title` VARCHAR( 255 ) NOT NULL, `Authors` VARCHAR( 150 ) NOT NULL, `JName` VARCHAR( 30 ) NOT NULL, `JVolume` INT( 8 ) NOT NULL, `JYear` YEAR( 4 ) NOT NULL, `JPage` INT( 11 ) NOT NULL, `Abstract` text, UNIQUE KEY `BibID` ( `BibID` ) , KEY `PubID` ( `PubID` ) ) ENGINE = MYISAM DEFAULT CHARSET = latin1;
It is generally a good idea to back up these databases on a regular basis – to save oneself from the pain of re-entering everything if something were to go wrong. You may refer to one of my previous posts that discusses backing up and restoring MySQL databases in detail.
#2. User Side: publications.cgi
Following one of the requirements as mentioned before, this page must display all publications when no query is submitted (default view) and display only those publications (with abstract) when a query is submitted. The part below is the code for default view.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | #! /usr/bin/perl # publications.cgi (PART #1) # CGI script to search the database # Modules being used use DBI; use CGI; # Make a CGI object and retrieve information from the form $inputform = new CGI; print $inputform->header; # Get values from the form $year = $inputform->param("year"); $title = $inputform->param("title"); $author1 = $inputform->param("author1"); $author2 = $inputform->param("author2"); $bo1 = $inputform->param("BO1"); $bo2 = $inputform->param("BO2"); $bo3 = $inputform->param("BO3"); $ffill = $inputform->param("ffill"); # If the variable 'ffill' is empty, then display the form if ((!($ffill))) { print << "EOF"; <!-- www.w3c.org standard --> <!-- HTML begins --> <!-- HEAD section --> <!-- TITLE section --> <!-- BODY section --> <!-- Group Header --> |
YOUR GROUP NAME
Publications
EOF
# Connect to the database and perform the SQL query
$dbh = DBI->connect(‘dbi:mysql:einstein_research:localhost’,’einstein_web’,’PASSWORD’) or die “Error”;
$sql1 = “SELECT * FROM publications ORDER BY JYear DESC, “;
$sql = $sql1 . “JName ASC, JVolume DESC, JPage DESC, Title”;
$query = $dbh->prepare($sql);
$query->execute;
$nresults = $query->rows;
# Display the results
if ( $nresults > 0 ) {
print << “EOF”;
1 2 3 4 5 6 7 8 9 10 11 12 13 | EOF $id=1; while(($PubID,$BibID,$Title,$Authors,$JName,$JVolume,$JYear,$JPage,$Abstract)=$query->fetchrow()) { print << "EOF"; EOF $id++; } print << "EOF"; |
# | BibID / Title / Authors / Citation (Last-to-first, with Journals alphabetically sorted) |
$id |
$BibID | $Title $Authors $JName, $JVolume, $JPage ($JYear) |
EOF
} else {
print ”
Search Results
\n”;
print “Sorry, no records were found!“;
}
print << “EOF”;
1 2 3 4 5 | <!-- HTML ends --> EOF exit; } |
The part below contains the code that takes care of search-results part.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | # publications.cgi (PART #2) # If the variable 'ffill' is not empty, then query the database # and display results print << "EOF"; <!-- www.w3c.org standard --> <!-- HTML begins --> <!-- HEAD section --> <!-- TITLE section --> <!-- BODY section --> <!-- Group Header --> |
YOUR GROUP NAME
Publications
EOF
# If the variable ‘ffill’ is not empty, display the search results
# Connect to the database and perform the SQL query
$dbh = DBI->connect(‘dbi:mysql:einstein_research:localhost’,’einstein_web’,’PASSWORD’) or die “Error”;
$sql1 = “SELECT * FROM publications WHERE JYear LIKE \”$year\” $bo1 “;
$sql2 = $sql1 . “Title LIKE \”%$title%\” $bo2 Authors LIKE \”%$author1%\” $bo3 “;
$sql3 = $sql2 . “Authors LIKE \”%$author2%\” ORDER BY JYear DESC, JName ASC, “;
$sql = $sql3 . “JVolume DESC, JPage DESC, Title”;
$query = $dbh->prepare($sql);
$query->execute;
$nresults = $query->rows;
# Display the results
if ( $nresults > 0 ) {
print << “EOF”;
Search Results
Your query matched $nresults result(s)
1 2 3 4 5 6 7 8 9 10 11 12 13 | EOF $id=1; while(($PubID,$BibID,$Title,$Authors,$JName,$JVolume,$JYear,$JPage,$Abstract)=$query->fetchrow()) { print << "EOF"; EOF $id++; } print << "EOF"; |
# | BibID / Title / Authors / Citation / Abstract (Last-to-first, with Journals alphabetically sorted) |
$id |
$BibID | $Title $Authors $JName, $JVolume, $JPage ($JYear) $Abstract |
EOF
} else {
print ”
Search Results
\n”;
print “Sorry, no records were found!“;
}
print << “EOF”;
1 2 3 4 5 6 | <!-- HTML ends --> EOF # Close database connection $dbh->disconnect; |
#3. Admin Side: pub_entry.cgi
Guidelines for using this are as follows:
- BibID
- Cannot be empty
- Maximum of 15 characters
- Must be UNIQUE
- Cannot be changed later
- Good way to compose this is by using first letters of authors’ last names along with year
(i.e., if R. J. Smith, A. S. Young and B. L. Spring published an article in 2006, BibID would be SYS2006.In case of single author, use Smith2006)
- If you expect to have more than one publication in a year by the same set of authors,
use SYS2006_0, SYS2006_1, and so on OR Smith2006_0, Smith2006_1, etc. - Required to delete/update an entry, if such a need arises
- Title
- Cannot be empty
- Maximum of 255 characters
- Can contain some HTML tags (<b>, <em>, <sup>, <sub>, etc)
- Use backslash ( \ ) to escape single-quotes ( ‘ )
- Authors
- Cannot be empty
- Maximum of 150 characters
- Separate authors by using ‘,’ (comma)
- Do not use ‘and’
- Journal :: Name
- Cannot be empty
- Maximum of 30 characters
- Can contain some HTML tags (<sup>, <sub>, etc)
- Journal :: Volume
- Cannot be empty
- Must be an integer
- Journal :: Year
- Cannot be empty
- Must be an integer
- Use all four digits to specify (like ‘2006’ instead of ’06’)
- Journal :: Starting Page
- Cannot be empty
- Must be an integer
- Abstract
- Can be empty
- Maximum of 255 characters
- Can contain some HTML tags
(<b>, <em>, <sup>, <sub>, etc) - Use backslash ( \ ) to escape single-quotes ( ‘ )
- Journal :: PDF Version
- Cannot be empty
- PDF document MUST have the SAME name as BibID
- MUST be PDF (not just the filename extension)
- Process DOES NOT check to make sure it is PDF
The code is split into two parts – default view is to just display a form. When properly submitted, it makes an entry into the database. Code for default view is below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | #! /usr/bin/perl # pub_entry.cgi (PART #1) # CGI script to make an entry into publication # Modules being used use DBI; use CGI; use CGI::Carp qw ( fatalsToBrowser ); use File::Basename; # Make a CGI object and retrieve information from the form $inputform = new CGI; print $inputform->header; # Assign form-values to local variables $bibid = $inputform->param("bibid"); $title = $inputform->param("title"); $authors = $inputform->param("authors"); $jname = $inputform->param("jname"); $jvolume = $inputform->param("jvolume"); $jyear = $inputform->param("jyear"); $jpage = $inputform->param("jpage"); $abstract = $inputform->param("abstract"); $jpdfdoc = $inputform->param("jpdfdoc"); $efill = $inputform->param("efill"); # If variable 'efill' is empty, then display the form if (!($efill)) { print << "EOF"; <!-- www.w3c.org standard --> <!-- HTML begins --> <!-- HEAD section --> <!-- TITLE section --> <!-- BODY section --> <!-- Group Header --> |
YOUR GROUP NAME
Publications :: Database Management :: Entry
1 | <!-- HTML ends -->EOF exit; } |
The details regarding uploading a document via PERL & CGI are contained in one of my previous posts. Code for entering the above information into the database follows below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | # pub_entry.cgi (PART #2) # If variable 'efill' is not empty, then insert the data # into the database print << "EOF"; <!-- www.w3c.org standard --> <!-- HTML begins --> <!-- HEAD section --> <!-- TITLE section --> <!-- BODY section --> <!-- Group Header --> |
YOUR GROUP NAME
Publications :: Database Management :: Entry
EOF
# Connect to the database and perform the SQL query
$db = DBI->connect(‘dbi:mysql:einstein_research:localhost’,’einstein_web’,’PASSWORD’) or die “Error”;
$sql1 = “INSERT INTO publications VALUES (”, ‘$bibid’, ‘$title’, “;
$sql2 = $sql1 . “‘$authors’, ‘$jname’, ‘$jvolume’, ‘$jyear’, ‘$jpage’, “;
$sql = $sql2 . “‘$abstract’)”;
$query = $db->prepare($sql);
$query->execute;
# PDF upload part
# 5MB limit on the size of the document
$CGI::POST_MAX = 1024 * 1024 * 5;
# Characters that are allowed to be part of the filename
my $safe_characters = “a-zA-Z0-9_.-“;
# Update location
my $upload_location = “/var/www/html/pdf”;
my $filename = $inputform->param(“jpdfdoc”);
if ( !$filename ) {
print $inputform->header ( );
print << “EOF”;
There was a problem uploading the PDF
EOF
exit;
}
# Clean up the filename – remove any ‘path’ and split the filename into
# basename and extension
my ( $name, $path, $extension ) = fileparse ( $filename, ‘\..*’ );
$filename = $name . $extension;
# Replace blank space in filename with ‘underscore’
$filename =~ tr/ /_/;
# Remove any ‘not safe’ characters
$filename =~ s/[^$safe_characters]//g;
# Untaint the filename
if ( $filename =~ /^([$safe_characters]+)$/ ) {
$filename = $1;
} else {
die “Filename contains invalid characters”;
}
my $upload_filehandle = $inputform->upload(“jpdfdoc”);
open ( UPLOADFILE, “>$upload_location/$filename” ) or die “$!”;
binmode UPLOADFILE;
while ( <$upload_filehandle> ) {
print UPLOADFILE;
}
close UPLOADFILE;
print << “EOF”;
Data was successfully entered into the database. Click
here to make another entry.
1 2 3 4 5 6 | <!-- HTML ends --> EOF # Close Database Connection $db->disconnect; |
#4. Admin Side: pub_update.cgi and pub_updated.cgi
Often times, it becomes necessary to update an entry (author names, citation, abstract, etc.) and to do so, the appropriate entry must be retrieved from the database. Code for pub_update.cgi follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | #! /usr/bin/perl # pub_update.cgi # CGI script to retrieve a publication from the database # for update # Modules being used use DBI; use CGI; # Make a CGI object and retrieve information from the form $inputform = new CGI; print $inputform->header; # Assign form-values to local variables $bibid = $inputform->param("bibid"); $rfill = $inputform->param("rfill"); # If variable 'rfill' is empty, then display the form if (!($rfill)) { print << "EOF"; <!-- www.w3c.org standard --> <!-- HTML begins --> <!-- HEAD section --> <!-- TITLE section --> <!-- BODY section --> <!-- Group Header --> |
YOUR GROUP NAME
Publications :: Database Management :: Retrieve
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <!-- HTML ends --> EOF exit; } # If variable 'rfill' is not empty, retrieve data from the database print << "EOF"; <!-- www.w3c.org standard --> <!-- HTML begins --> <!-- HEAD section --> <!-- TITLE section --> <!-- BODY section --> <!-- Group Header --> |
YOUR GROUP NAME
Publications :: Database Management :: Retrieve
EOF
# Connect to the database and perform the SQL query
$db = DBI->connect(‘dbi:mysql:einstein_research:localhost’,’einstein_web’,’PASSWORD’) or die “Error”;
$sql = “SELECT * FROM publications WHERE BibID=’$bibid’ LIMIT 1”;
$query = $db->prepare($sql) or die “Error”;
$query->execute;
while(($PubID,$BibID,$Title,$Authors,$JName,$JVolume,$JYear,$JPage,$Abstract)=$query->fetchrow()) {
print << “EOF”;
EOF } print << “EOF”;
1 | <!-- HTML ends -->EOF # Close Database Connection $db->disconnect; |
pub_update.cgi takes all the information and passes it over to pub_updated.cgi, which updates the record. Code for pub_updated.cgi follows below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | #! /usr/bin/perl # pub_updated.cgi # CGI script to update an entry in the database # Modules being used use DBI; use CGI; # Make a CGI object and retrieve information from the form $inputform = new CGI; print $inputform->header; # Assign form-values to local variables $bibid = $inputform->param("bibid"); $title = $inputform->param("title"); $authors = $inputform->param("authors"); $jname = $inputform->param("jname"); $jvolume = $inputform->param("jvolume"); $jyear = $inputform->param("jyear"); $jpage = $inputform->param("jpage"); $abstract = $inputform->param("abstract"); print << "EOF"; <!-- www.w3c.org standard --> <!-- HTML begins --> <!-- HEAD section --> <!-- TITLE section --> <!-- BODY section --> <!-- Group Header --> |
YOUR GROUP NAME
Publications :: Database Management :: Retrieve
EOF
# Connect to the database and perform the SQL query
$db = DBI->connect(‘dbi:mysql:einstein_research:localhost’,’einstein_web’,’PASSWORD’) or die “Error”;
$sql1 = “UPDATE publications SET Title=’$title’,Authors=’$authors’,”;
$sql2 = $sql1 . “JName=’$jname’,JVolume=’$jvolume’,JYear=’$jyear’,”;
$sql = $sql2 . “JPage=’$jpage’,Abstract=’$abstract’ WHERE BibID=’$bibid’ “;
$query = $db->prepare($sql);
$query->execute;
print << “EOF”;
Data was successfully updated in the database. Click
here to update another entry.
1 2 3 4 5 6 | <!-- HTML ends --> EOF # Close Database Connection $db->disconnect; |
#5. Admin Side: pub_delete.cgi
Seldom it becomes necessary to delete an entry from the database (a reference article entered in by mistake as a publication, etc.) and the code for pub_delete.cgi follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | #! /usr/bin/perl # pub_delete.cgi # CGI script to delete an entry from the database # Modules being used use DBI; use CGI; # Make a CGI object and retrieve information from the form $inputform = new CGI; print $inputform->header; # Assign form-values to local variables $bibid = $inputform->param("bibid"); $dfill = $inputform->param("dfill"); # If variable 'dfill' is empty, then display the form if (!($dfill)) { print << "EOF"; <!-- www.w3c.org standard --> <!-- HTML begins --> <!-- HEAD section --> <!-- TITLE section --> <!-- BODY section --> <!-- Group Header --> |
YOUR GROUP NAME
Publications :: Database Management :: Delete
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <!-- HTML ends --> EOF exit; } # If variable 'dfill' is not empty, then delete an entry # from the database print << "EOF"; <!-- www.w3c.org standard --> <!-- HTML begins --> <!-- HEAD section --> <!-- TITLE section --> <!-- BODY section --> <!-- Group Header --> |
YOUR GROUP NAME
Publications :: Database Management :: Delete
EOF
# Connect to the database and perform the SQL query
$db = DBI->connect(‘dbi:mysql:einstein_research:localhost’,’einstein_web’,’PASSWORD’) or die “Error”;
$sql = “DELETE FROM publications WHERE BibID=’$bibid’ LIMIT 1”;
$query = $db->prepare($sql) or die “Error”;
$query->execute;
print << “EOF”;
Entry was successfully deleted from the database. Click
here to delete another entry.
1 2 3 4 5 6 | <!-- HTML ends --> EOF # Close Database Connection $db->disconnect; |
#6. Admin Side: Restricting Access To Admin Interface
There are some ways of achieving this – to prevent unauthorized personnel from messing with databases and files.
- Password protect the admin folder – allow only a certain user from any machine
- IP address/Hostname based restriction – allow any user (preferably a group member) to access the admin interface from certain machine(s).
- Combination of #1 & #2 – allow only certain users from certain machines.
A simple Google!ing for password protection .htaccess .htpasswd should result in a good number of decent documents. But do check/discuss your approach with your systems administrator(s) – to make sure that it can be applied, is feasible and less mis-usable under existing circumstances.
Screenshots
The screenshots below were generated after incorporating the style sheets (CSS) that are in-line with Michigan Tech theme. The code in the above sections, however, results in very plain, bare-bone HTML pages. With a basic, working knowledge of CSS, it should not be too difficult to spice up the appearance:
Demonstration
Live demo of this code, only the publications.cgi, is here. Others, as can be expected, are hidden in a secure folder.
One Reply to “Storing And Querying Information with PERL-MySQL”