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:

<html>
<head>
<title>Polling System</title>
</head>

<body>
<h1>My Poll</h1>
<?php
//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
if(!$db->select_db('one'))
    
//create the database
    
$db->query('create database one');
    
//select the databasw to work with
$db->select_db('one');
        
//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
if($_GET['action']=='Vote')
{
    
$option1=$_GET['option1'];
    
$option2=$_GET['option2'];
    
$option3=$_GET['option3'];
    
//--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");

        
$result=$result->fetch_row();
        
$op1=$result[1];
        
$op2=$result[2];
        
$op3=$result[3];
    
        
        
//increment the voted option
        
if($option1=='voted'$op1++;
        elseif(
$option2=='voted'$op2++;
        elseif(
$option3=='voted'$op3++;
        
        
//save the updated values
        
$db->query("update poll set option1='$op1', option2='$op2', option3='$op3'");
        
        
//redirect to results page
        //by setting the $_GET var
        
$_GET['action']='Results';
    }
}
if(
$_GET['action']=='Results')
{
    
//fetch initial values of polls in DB
    
$result=$db->query("select * from poll");

    
$result=$result->fetch_row();
    
$op1=$result[1];
    
$op2=$result[2];
    
$op3=$result[3];
        
    
//close DB
    
$db->close();
//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>

<?php
//closing of PHP blocks may be done this way
}
else
{
//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>
      <p> 
    <input type="radio" name="option1" value="voted" />
        Very Good!</p>
      <p> 
        <input type="radio" name="option2" value="voted" />
        Not Bad...</p>
      <p> 
        <input type="radio" name="option3" value="voted" />
        Bad...</p>
      <p>
        <input name="action" type="submit" id="action" value="Vote" />
      </p>
    </form>
    <p><a href="?action=Results">Show Results</a></p>
    </body>
    </html>
<?php
}
?>

Previous Articles:

Popular posts from this blog

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 {   ...

How to Create an HTML Form Linked with MySQL Database in PHP

If you're looking for example code and detailed discussion on how to create an HTML form that stores data in a MySQL database using PHP then this post might be what you're looking for. I assume that you're familiar with basic HTML, CSS, PHP coding, and  MySQL. I am going to divide this small project into two parts: The HTML form itself that takes input from the user and the PHP script that saves it into the database A table that displays the user-added data that has been saved in the database. We'll be dealing with the first part in this tutorial. Again I'd like to break this problem into a few parts so that it's easier for you to understand and probably gives you an insight into how breaking up a problem into smaller chunks can help make things clearer in your mind. Let's think about it, there is an HTML form (that is HTML code), then there is the PHP code that deals with the user-input data, and the MySQL database itself. For this tutorial, we'll b...

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 ...