Skip to main content

DB2 and open source: Web polling with DB2, PHP, and Linux

Cast your votes here

Aron Lurie (aron@lurie.biz), 7th Grader, Middle School/Hebrew College
Author photo
Aron was completing 7th grade as this article was being written. He has had a Web development business for two years. Aron wrote the PHP code for this article for one of his clients. He works for Hebrew College as the Assistant webmaster for their high school. He is also the webmaster for his local USY chapter, and he volunteers his Friday afternoons to work on a Web site for the local public school system. Aron runs a dual boot system, but boots into Fedora Linux the vast majority of the time. The top of his wish list is a processor fast enough to do justice to Core 2.
Marty Lurie (lurie@us.ibm.com), Systems Engineer, IBM, Software Group
Marty Lurie started his computer career generating chads while attempting to write Fortran on an IBM 1130. His day job is in Systems Engineering for IBM's Data Management Division, but if pressed he will admit he mostly plays with computers. His favorite program is the one he wrote to connect his Nordic Track to his laptop (the laptop lost two pounds, and lowered its cholesterol by 20 percent). Marty is an IBM-certified DB2 DBA, IBM-certified Business Intelligence Solutions Professional, Linux+ Certified Administrator and an Informix-certified Professional. He can be reached at lurie at us.ibm.com.

Summary:  Web polling or voting provides a great way to get feedback from visitors to your site. This article shows you how to add this feature to your Web site using IBM® DB2® Universal Database™(UDB), Hypertext Preprocessor (PHP), and Linux™. You'll look at some of the design aspects of how to conduct a meaningful poll and then you will dive into the technical details. The design you'll explore includes using a database to store the polling information and the PHP scripting language to vote, create, manage, and review the polls.

Date:  19 Aug 2004
Level:  Introductory
Activity:  1409 views

Why Web polling?

Get feedback from your visitors

Web polling or voting provides a great way to get feedback from visitors to your site. This article explains how to add this feature to your Web site. You will look at some of the design aspects of how to conduct a meaningful poll and then dive into the technical details. The design you'll explore includes using a database to store the polling information and the PHP scripting language to vote, and also create, manage, and review the polls. Adding this capability to your Web site is very straightforward; keep in mind that the code presented here was created by a 12 year old.

A sample poll

If you've used a Web browser you've probably already seen a Web poll and even voted in one. Just in case, here is a sample poll in Figure 1. You will examine the dubious quality of this sample poll question in the next section. It suffers from "leading the witness" syndrome.


Figure 1. Sample poll
Sample poll

Many ways exist to do polls, and they can be implemented with a database or be as simple as generating e-mails to the poll administrator.The more active the poll, the more important the database technology becomes for managing the transaction workload, results, and reporting.

Fibs, lies, statistics, and polls

Statistics are often maligned, but provide great insight into your poll data. How valid is the poll you are running? It depends on how the questions and answers are phrased and what conclusions you are trying to draw from your poll. Great polling errors have made the front page of the newspaper on several occasions.

Since this is a computer article instead of a statistics article here is the abridged and condensed version of polling statistical experimental design. Follow this list of guidelines to try to get an understanding of how your site visitors really think. Do the opposite of what is suggested here if you are trying to use the poll to push your personal agenda. The poll in Figure 1 is a parody of poll question and answer design.

  • Provide neutral questions that don't have judgmental adjectives
  • Provide a range of answers that include a wide spectrum of opinions
  • Include an option of "none of the above" or write-in answers
  • Try to a achieve a random sample of the target audience
  • Don't assume your results are valid if a large number of people voted
  • Don't assume your results are valid if a small number of people voted
  • Remember your poll is just a sample of the people who:
    • Came to your site
    • Chose to vote in the poll

A large random sample provides reliable results in most cases. If your sample is small you may still have a valid poll if your target population is small. For example, if you are doing a poll of all the twins born on January 1, 1904, your current living target population size is very small, so if you get any participation in the poll it could represent 50 percent or 100 percent of the living target population.

Even with a large number of responses you may not have a valid result. If the poll subject is political or religious your Web site may be circulated to activist groups on both sides of the issue. Instead of getting a random sample, your poll will reflect the activist groups' organizational skills and energy level.


Poll system architecture

The browser, Web server, and database server are illustrated in Figure 2. For this article all components were running on Red Hat Enterprise Server v3. The supported Linux distributions for DB2 are listed here:
http://www-306.ibm.com/software/data/db2/linux/validate

You could implement Web polling on Win32 if you chose.


Figure 2. Diagram of the browser, the Web server, and the database
Browser, Web server, and database

Summary of steps to implement Web polling

1. Collect the components

You'll need Apache, PHP, and DB2 for Linux. This can be implemented on other platforms, but those won't be covered here.

2. Install and configure the components

Ample documentation exists; however, this article covers specifically what is unique to this system.

3. Install and configure the source code

To do this, you will need to download the source code zip file pollsource.zip . You will then need to un-tar the files into the folder that you set up to be the Apache "DocumentRoot". By default, on a Red Hat Linux system, the DocumentRoot will be /var/www/html/.

4. Store poll data

You will create the tables and relationships to store the poll information. Using SQL inserts you'll then create a simple poll. The poll maintenance PHP screens, created later are the primary way of adding and maintaining polls, you won't have to write a lot of SQL to keep your site going.


The components

The three key parts for this project are the Apache Web Server, the PHP programming environment, and the DB2 server. There are already lots of documents on how to install and configure these components, so in this article, you will focus only on the unique aspects of installing this environment. The links to the installation and configuration references are discussed below.

Apache Web Server

Apache is available at www.apache.org. Your Linux distribution may include an Apache environment. You will need the apache/bin/apxs binary to build the PHP environment. If this isn't on your system you can install it from rpm or build Apache from the source code.

PHP

PHP is available at www.PHP.net. Your linux distribution may already include a PHP environment. However in order to use DB2 with PHP, you must recompile PHP to include Open Database Connectivity (ODBC) support. You can find instructions on how to do this at:
http://www-106.ibm.com/developerworks/db2/library/techarticle/scott/0614_scott.html

DB2 UDB

The DB2 Quick Beginnings steps through the install and configuration. To verify your installation and the ODBC connection, change to the sample/cli directory and use the bldapp script to build the dbinfo sample. Once you have this running you'll be ready to connect PHP to the database.


Connect the components

A very good article on how to connect Apache, PHP, and DB2 is available at:
http://www-106.ibm.com/developerworks/db2/library/techarticle/scott/0614_scott.html

Set up the database for use

For safety and security reasons, you aren't going to be connecting to the database as the administrator. Instead, login as db2inst1 for the moment, and run DB2. Once that is done, run the following three commands:

db2 => create database phpweb
db2 => connect to phpweb
db2 => grant dbadm on database to phpweb

Now, you can log out of db2inst1.


Store poll data

You are going to put your poll questions and results in a database, specifically DB2. Important information belongs in a database. This is for access, update, backup, historical access, and ease of manageability. To store the poll-related information you need a database schema. Here are the tables you use:

-Table name: polls
	The columns in the "polls" table are:
	pollkey - the number of the poll, which is the primary key.
	question - the text of the poll question in a varchar field.
	pollstartdate - the date the poll started. 
	pollenddate - the date designated for this poll to end.

Table name: pollresponses
	The columns in the "pollresponses" table are:
	responsekey - a unique identifier for the response
		which is the primary key.
	pollkey - the reference to the "polls" table to assign
		responses to a poll question. 
	responsenum - the number to order the responses for a particular
		question.
	responsetext - the text of the response.
	votes - the count of votes for the response.

To create these tables use the following SQL:


Listing 1. Schema for storing poll questions and responses.

CONNECT TO PHPWEB;

CREATE TABLE polls (
    pollkey int primary key,
    question varchar(500),
    pollstartdate date,
    pollenddate date
);

CREATE TABLE pollresponses (
    responsekey int primary key,
    pollkey int references polls,
    responsenum int,
    responsetext varchar(300),
    votes int
);

-- create an index on the pollresponse pollkey column
-- since most joins use this to join to the polls table

create index i_response  on pollresponses ( pollkey );

--Example of creating a new poll

INSERT INTO polls VALUES 
(1, 'What do you think of this perfect article?', '2004-05-30','2005-01-01');

--The number 1 is the number of the poll, which is the primary key
--The question 'What do you think of this perfect article?' 
-- is the question the poll will 
--be asking.
--The date '2004-05-30' is the date the poll started. 
--The date '2004-03-22 is the date designated for this poll to end. 
--All dates must be in the format 'YYYY-MM-DD'.


--Example of adding a response that can be chosen by the poll-ee.

INSERT INTO pollresponses VALUES (1, 1, 1, 'It''s absolutely amazing!', 0);

--The first 1 is the number of the response out of all the responses for 
-- all the polls. 
--This is the primary key.
--The second 1 is the number of the primary key of the poll 
-- that this will be a response to.
--The third 1 is the number to order the responses that will 
-- appear within the specific poll that the response belongs to.
--'It''s absolutely amazing' is the text of the response
--The 0 is the amount of votes the response has. This number 
--should ALWAYS start at zero, and will be changed by the PHP script.

--Adding another response:

INSERT INTO pollresponses VALUES (2,1,2, 'It''s good', 0);


Now that you have these tables configured you can validate the overall system by displaying the poll Web page in a browser.


Connect to the database with PHP

The PHP scripts, when requested by a Web browser, are rendered into HTML by the PHP module running in the Apache server. The first simple script here will open a database connection and confirm that with a message to the browser. This could also be run from the command line with the php command.

The userid for this environment is phpweb not the dbadm or root user. The privileged accounts should only be used when needed, not for normal production. Please don't use a password phpweb1 for your production environment!


Listing 2. Sample script to open a database connection with PHP. to database.

<?php
        $dbname = "PHPWEB";
        $username = "phpweb";
        $password = "phpweb1";
 
        // odbc_pconnect returns 0 if the connection attempt fails
        // otherwise it returns a connection ID used by other ODBC functions
                echo ( "attempt connect.....\n " );
        $conn = odbc_pconnect ( $dbname, $username, $password );
 
        if ( $conn == 0 ) {
                echo ( "Connection to database failed." );
		//If connection failed, show what the error message was:
                $sqlerror = odbc_errormsg ( $conn );
                echo ( $sqlerror );
        }
                echo ( "connect ok" );

?>

Running this PHP program in the Apache server environment produces the following screen:


Figure 3. Test connect screen
Test connect screen

With this working successfully you are now ready to install and run the PHP code of the polling system.


The PHP polling tool

There are two parts to the polling tool; The actual voting scripts, and the maintenance tools. You will explore these two parts separately.

The code to run the poll is found in the zip file. The zip file includes the poll scripts and the tools to manage the polls. You will want to make changes to the scripts to fit your needs.


The voting scripts

The "voting scripts" includes:

  • The index.php file, which either sends the user to a place where they can choose which poll they want to vote on, or sends them to the voting screen for the only available poll.
  • The choosevote.php file, which allows users to choose, from a list, which poll they want to vote on.
  • The vote.php file, which is the voting screen shown in Figure 4.
  • The pollresults.php file, which allows users to view the results of the poll without actually voting.
  • The processvote.php file, which processes the user's vote by updating the database, and then displays the results.

The output from running the vote screen (vote.php) looks like this:


Figure 4. Sample vote screen
Sample vote screen

When the vote button is clicked, the processing advances to the processvote.php script. This will update the database tables.

How do you add new polls to the Web site? You can't expect the community that wants to use the polling system to write SQL statements to manage the questions and answers in the tables.

An elegant solution to poll maintenance is to provide Web pages that manage the Web polls. Now, examine how to do poll maintenance without leaving the Web browser in the next section.

The maintenance scripts

The "maintenance scripts" includes:

  • The poll-create1.php, poll-create2.php, and poll-create3.php files, which are the tools to create a new poll.
  • The poll-drop1.php and poll-drop2.php files, which are the tools to remove a poll.
  • The poll-manage1.php file, which is the "home page" of all these tools. This page provides a detailed listing of all the polls, plus a link to the creation, drop, and vote tools.

Poll maintenance includes creation and destruction. The tool to create the poll has 3 screens. A screenshot of the poll creation tool can be found in Figure 5.

The maintenance screens shown below are mostly self explanatory. The source for these screens is in the zip file. Each figure's label includes the php file name. This should make life much easier when looking at the source in the zip file.


Figure 5. Main management tool - poll-manage1.php
Main management tool

Figure 6. First poll creation tool screen - poll-create1.php
First poll creation tool screen

Figure 7. Poll removal tool - poll-drop1.php
Poll removal tool

The magic behind the polls

Now that you have looked at the two separate parts to the polling system and the files that power them, take a look at the source code that powers the pages. Once again, you will look at the two parts separately.

The voting scripts

When the user comes to the Web site, the first page they will encounter is one of the voting scripts, which happens to be index.php. index.php will connect to the database, and check to see how many entries there are in the poll database that haven't expired. If there is one entry, it will forward the user to vote on that one poll at vote.php. Otherwise, it will send the user to choosevote.php, where they will either choose which of multiple polls they want to vote on, or learn that there are no current polls. The source code for index.php is shown below in Listing 3.


Listing 3. The source code of index.php

<?php
                                                                                
$dbname = "PHPWEB";
$username = "phpweb";
$password = "phpweb1";
                                                                                
$dbh = odbc_pconnect ( $dbname, $username, $password );
                                                                                
$today = date("Y-m-d");
$sql = "select * from polls where  pollenddate > '$today' order by pollkey";
$pollexec = odbc_exec($dbh , $sql);
$rows = odbc_num_rows($pollexec);
                                                                                
//if there is one current poll
if ($rows == "1")
{
   //sends the user to vote on that poll
   $data = odbc_fetch_object($pollexec);
   header("Location: vote.php?pollkey=$data->POLLKEY");
   exit;
}
//if there is more than one or zero current polls
else
{
   //sends the user to choosevote.php
   header("Location: choosevote.php");
   exit;
}
                                                                                
?>


As mentioned earlier, from index.php the user will go one of two ways. They will either go to vote.php, or choosevote.php. However, if they go to choosevote.php because there are multiple polls, once they click on a link it will take them to vote.php. Once the user is at vote.php, they will either vote, or look at the current results. Because the voting script is more interesting (and complex), you will look at that in more detail. The script, titled processvote.php processes the user's vote by adding it to the database, and then displaying the results the same way that pollresults.php does. The source code of processvote.php (32 lines) can be found below in Listing 4.


Listing 4. The source code of processvote.php

<?php
$dbname = "PHPWEB";
$username = "phpweb";
$password = "phpweb1";
$conn = odbc_pconnect ( $dbname, $username, $password );
//if the user doesn't choose an answer...
if($_POST[vote] == 0){
echo "You did not choose an answer.\n ";
die("<center><h2> Please go back and select one.");
}
$sqlstr= "select * from pollresponses where  responsekey = $_POST[vote]";
$getvotesnum = odbc_exec($conn, $sqlstr );
$votesnum = odbc_fetch_object($getvotesnum);
$today=date("Y-m-d");
$sqlstr= "select * from polls where pollkey=$votesnum->POLLKEY";
$getexpire=odbc_exec($conn, $sqlstr);
$expiredata=odbc_fetch_object($getexpire);
if ($expiredata->POLLENDDATE > "$today"){
$newvotesnum = $votesnum->VOTES+1;
$vote = odbc_exec($conn, "update pollresponses set 
        votes = $newvotesnum where responsekey = $_POST[vote]");
	$sql = "select * from pollresponses where pollkey = $_POST[pollkey] ";
	$sql .=	"order by responsekey";
$execute= odbc_exec($conn, $sql);
$rows = odbc_num_rows($execute);
echo "<center><h1>Poll Results</h1>";
echo "<h3>Question: $expiredata->QUESTION</h3>";
echo"<table name='table' border='0'>";
for ($i=1; $i<=$rows; $i++)
{
   //retrieve all the responses and their data, and display it
   $data = odbc_fetch_object($execute, $i);
   echo "<tr valign='center' rowspan='1' colspan='1' align='right'>";
   echo "<td valign = 'center' align = 'right' rowspan='1' colspan='1'>";
   echo "$data->RESPONSETEXT:</td><td>$data->VOTES votes";
   echo "</td></tr>";
}
echo "</table>";
echo "<br><a href='index.php'>Back To Poll Index</a>";
}
//if the poll has expired
else
{
echo "<center>Your vote was not processed because this poll has expired.";
echo "< br>To get to a list of polls that are not expired please click ";
echo "< a href='choosevote.php' class='primary'>here</a><br>";
echo "To view the results for this poll, please click ";
echo "<a href='pollresults.php?pollkey=$expiredata->POLLKEY'>here</a>.";
}
?>


Now that you have looked at some of the source code of the voting scripts, you can move on to the maintenance scripts, and you can see the source code for one of the create tool screens and for the main maintenance tool.

The maintenance scripts

Poll maintenance is performed by an administrator. The pages to perform the maintenance should be password protected. To configure Apache to use a password for a particluar directory look at the documentation for .htaccess ,AuthType, and the command htpasswd.

The structure of the maintenance scripts are not very complex. There are three tools, each with an average two pages of source code per tool. This time, it is the Web site administrator, not the user, who will be doing the browsing.

Unlike the voting tools, this group of tools does not have an index.php file; however, one of its tools acts as the main admin Web site, with links to all the other tools. In this article, you will not see the source code for that tool, but you will see the source code for two others--the create and drop tools.

First, look at the create tool. The create tool has three screens, but here, you will only examine the second one in detail. The second screen enters all of the information from the first page into the database, and then collects more information from the user, which will be entered into the database in the third page. The source code for this page, poll-create2.php, is below in Listing 5.


Listing 5. The source code of poll-create2.php

<?php
$dbname = "PHPWEB";
$username = "phpweb";
$password = "phpweb1";
$conn = odbc_pconnect ( $dbname, $username, $password );

//in this part of the script, it will add the question, startdate, 
// and enddate to the database

//the @ sign before the function tells the function not to 
// output any error messages or warnings
$pollkeyexec = @odbc_exec($conn, "select * from polls order by pollkey");
$rows2 = @odbc_num_rows($pollkeyexec);
$keydata2 = @odbc_fetch_object($pollkeyexec, $rows2);
$pollkey = $keydata2->POLLKEY+1;
//these replace functions change the \' created by the php parser into a '' 
//that the database can read, and changes the \" from php to a " for the 
//database
$str1 = str_replace ("\'", "''", $_POST[question]);
$str2 = str_replace ('\"', '"', $str1);
$today = @date("Y-m-d");
$insertpoll = odbc_exec($conn,"insert into polls values 
             ($pollkey, '$str2', '$today', '$_POST[enddate]')");
                 
//in this part, the script will collect more information from the admin
                                                               
echo "<center><h1>Create a Poll</h1></center>";
echo "<center>";
echo "<form name = 'newpoll' action = 'poll-create3.php' method='post'>";
echo "<table border = '0'>";
                                                                                
for ($i=0; $i<$_POST[numresponses];$i++){
$i2 = $i+1;
echo "<tr valign='center' rowspan='1' colspan='1' align='right'>";
echo "<td valign = 'center' align = 'right' rowspan='1' colspan='1'>";
echo "Response $i2:</td><td align='left'>";
echo "<input type = 'text' name = 'response$i2' size = '70'>";
echo "<br></td></tr>";
}
echo "</table>";
echo "<input type='hidden' value='$_POST[numresponses]' name='numresponses'>";
echo "<input type = 'submit' value= 'Next Step'>";
echo "</form>";
?>


Now, take a look at the drop tool. This tool takes all the lines out of the polls and pollresponses tables where the data is relevant to whatever poll is being dropped. This source code, shown below in Figure 6, is self-explanatory, simplistic, and short.


Listing 6. The source code of poll-drop2.php

<?php

echo "<center><h1>Delete A Poll</h1>";
echo "<br><h3>Poll $_POST[pollkey] has been deleted</h3>";
$dbname = "PHPWEB";
$username = "phpweb";
$password = "phpweb1";
$conn = odbc_pconnect ( $dbname, $username, $password );
$sqlstr = "delete from pollresponses where pollkey=$_POST[pollkey]";
$query = odbc_exec($conn, $sqlstr);
$query2 = odbc_exec($conn, "delete from polls where pollkey=$_POST[pollkey]");
echo "<hr width='50%'>";
echo "<a href='poll-manage1.php'>Back to Poll Admin Tool</a>";

?>



Next steps

The environment described here is a good start to learn how to implement PHP and a simple Web polling system. This foundation can be customized to the needs of your site. Other polling PHP code exists, and the techniques used here will give you a good grounding in how polls work and how the data is stored in a database.

It is important to stay current on operating system, httpd, php, and DB2 maintenance, particularly as related to security issues. A subscription to Computer Emergency Readiness Team (CERT) is a good way to keep informed about security issues, see www.cert.org.

Good statistical experimental design will become the most important aspect of generating robust results from your Web polling system once the technical aspects are completed.



Download

NameSizeDownload method
pollsource.zip7.32 KB FTP | HTTP

Information about download methods


Resources

Learn

Get products and technologies

  • Now you can use DB2 for free. Download DB2 Express-C, a no-charge version of DB2 Express Edition for the community that offers the same core data features as DB2 Express Edtion and provides a solid base to build and deploy applications.

About the authors

Author photo

Aron was completing 7th grade as this article was being written. He has had a Web development business for two years. Aron wrote the PHP code for this article for one of his clients. He works for Hebrew College as the Assistant webmaster for their high school. He is also the webmaster for his local USY chapter, and he volunteers his Friday afternoons to work on a Web site for the local public school system. Aron runs a dual boot system, but boots into Fedora Linux the vast majority of the time. The top of his wish list is a processor fast enough to do justice to Core 2.

Marty Lurie

Marty Lurie started his computer career generating chads while attempting to write Fortran on an IBM 1130. His day job is in Systems Engineering for IBM's Data Management Division, but if pressed he will admit he mostly plays with computers. His favorite program is the one he wrote to connect his Nordic Track to his laptop (the laptop lost two pounds, and lowered its cholesterol by 20 percent). Marty is an IBM-certified DB2 DBA, IBM-certified Business Intelligence Solutions Professional, Linux+ Certified Administrator and an Informix-certified Professional. He can be reached at lurie at us.ibm.com.

Comments (Undergoing maintenance)



Trademarks  |  My developerWorks terms and conditions

Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Information Management, WebSphere
ArticleID=13692
ArticleTitle=DB2 and open source: Web polling with DB2, PHP, and Linux
publish-date=08192004
author1-email=aron@lurie.biz
author1-email-cc=
author2-email=lurie@us.ibm.com
author2-email-cc=

My developerWorks community

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere).

My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Special offers