Skip to main content

Creating a Simple Poll Script in PHP

OK, so again a useful script that we are going to create here. A polling system/script needs no introduction as it has been on the Web since long and is a good method to increase visitor activity on a website, apart from knowing their responses.

OK let’s start!

A polling system requires vote data to be stored, for that database (MySQL) would be the best choice.

Possible table structure for the database for a poll having three options would be

Logically thinking we know that only one row is required for a poll. Each time someone votes the value of the respective fields should be updated (incremented).

Initially the table would be like below:

Initial values in the table

After five votes to the first option, four to the second option and one to the third; the table would look like:

Values in the DB table after some votes

It should now be clear why we only need one row for a poll.

Designing the Poll

OK, now we’ll have to design the poll using an HTML table, some radio buttons and a submit button. You may write your poll question and the options besides the radio buttons. We’ll now have to integrate this to the script.

A sample Poll created by me:

A sample poll craeted by me

[NOTE: Radio boxes gives us the ability to let the visitor select ONLY ONE option from many.]

The Script

We are going to create the script such that it shows the Poll (HTML form) when no $_GET data is being passed, in other words visitor is requesting the Poll. It acts accordingly when someone is tries to see the results or vote their choice. After successful voting the result page is shown.

Here is the completed script:

<title>Polling System</title>

<h1>My Poll</h1>
//connect to MySQL 
//provide your 'USERNAME' and 'PASSWORD' 
//change 'localhost' to the MySQL server 
//host, if MySQL is on a sepearte server 
$db=new mysqli('localhost','-USER-','-PASS-');

//if this is the first time
//and database is not craeted
//create the database
$db->query('create database one');
//select the databasw to work with
//if table is not created, create it
if(!$db->query('select * from poll'))
//create a table for a Poll having three options
$db->query('create table poll (id int auto_increment primary key, option1 int, option2 int, option3 int)');
//create an initail row with value of 0 to each field
$db->query("insert into poll (option1, option2, option3) values (0,0,0)");

//someone is trying to vote
//--you may add more if needed
    //be sure to add same no. of radio buttons 
    //on the form too.
    //if any option was selected, then only save the vote
if($option1!='' || $option2!='' || $option3!='')
//fetch initial values of polls in DB
$result=$db->query("select * from poll");

//increment the voted option
//save the updated values
$db->query("update poll set option1='$op1', option2='$op2', option3='$op3'");
//redirect to results page
        //by setting the $_GET var
//fetch initial values of polls in DB
$result=$db->query("select * from poll");

//close DB
//using HTML with embedded PHP for ease
    <h3>Poll Results</h3>
    <p>How does it feel to be able to vote to your own Script?</p>
     <p>Very Good!: <?php echo $op1?></p>
     <p>Not Bad...: <?php echo $op2?></p>
     <p> Bad...: <?php echo $op3?></p>

//closing of PHP blocks may be done this way
//show poll form
    <h3>Cast Your Vote</h3>
    <form name="form1" id="form1" method="get" action="">
      <p>How does it feel to be able to vote to your own Script?</p>
    <input type="radio" name="option1" value="voted" />
        Very Good!</p>
        <input type="radio" name="option2" value="voted" />
        Not Bad...</p>
        <input type="radio" name="option3" value="voted" />
        <input name="action" type="submit" id="action" value="Vote" />
    <p><a href="?action=Results">Show Results</a></p>

Previous Articles:

Popular posts from this blog

Fix For Toshiba Satellite "RTC Battery is Low" Error (with Pictures)

RTC Battery is Low Error on a Toshiba Satellite laptop "RTC Battery is Low..." An error message flashing while you try to boot your laptop is enough to panic many people. But worry not! "RTC Battery" stands for Real-Time Clock battery which almost all laptops and PCs have on their motherboard to power the clock and sometimes to also keep the CMOS settings from getting erased while the system is switched off.  It is not uncommon for these batteries to last for years before requiring a replacement as the clock consumes very less power. And contrary to what some people tell you - they are not rechargeable or getting charged while your computer or laptop is running. In this article, we'll learn everything about RTC batteries and how to fix the error on your Toshiba Satellite laptop. What is an RTC Battery? RTC or CMOS batteries are small coin-shaped lithium batteries with a 3-volts output. Most laptops use

The Best Way(s) to Comment out PHP/HTML Code

PHP supports various styles of comments. Please check the following example: <?php // Single line comment code (); # Single line Comment code2 (); /* Multi Line comment code(); The code inside doesn't run */ // /* This doesn NOT start a multi-line comment block /* Multi line comment block The following line still ends the multi-line comment block //*/ The " # " comment style, though, is rarely used. Do note, in the example, that anything (even a multi-block comment /* ) after a " // " or " # " is a comment, and /* */ around any single-line comment overrides it. This information will come in handy when we learn about some neat tricks next. Comment out PHP Code Blocks Check the following code <?php //* Toggle line if ( 1 ) {      // } else {      // } //*/ //* Toggle line if ( 2 ) {      // } else {      // } //*/ Now see how easy it is to toggle a part of PHP code by just removing or adding a single " / " from th

C++ Hello World Program: Example Code with Detailed Explanation

C++ Hello World Program Output C++ is one of the most popular and powerful programming languages in the world. In this short article, we are going to go back to the basics and take a look at the simplest of the C++ program - the "Hello World" program which prints "Hello World!" to the screen. While you can set up a C++ environment very easily using one of the IDEs (including free ones such as CodeBlock  or Eclipse ), we'll be using a free online C++ compiler (or runner) for the sake of keeping things very simple and straightforward. C++ Hello World Program Code #include <iostream>   int main ( ) { // Comment std :: cout << "Hello World!" ; return 0 ; } Line-by-line Explanation C++ is a vast and very flexible language and a lot of functionality is offered by different libraries which we can include at the start of the program depending on what we need to do. Anything starting with a pound sign # is called a preprocessor