Tutorial: Building a Poll with PHP

I wanted to put together a little tutorial that shows the power of saving data to a jSON file. Introduced in PHP 5 were a few key methods that made this much easier (json encode, json decode). Here is a little tutorial that shows how to create a poll in PHP. We will save the poll question/answers and results in a jSON file. So for this poll we won’t need a database, rather the jSON file will be our database!

The Logic & Data

Lets start by creating a new PHP document index.php. We first start with making sure that the file where we will save the jSON data exists. Without this file our poll will not work so It’s important that we make sure its avaiable before trying to load the data.

if (file_exists('poll-data.json')) {
    // File Exists
}else{
    // The file was missing, stop everything!
    echo 'Missing poll-data.json file.';
    die;
}

We then load the jSON file into a variable then turn the jSON string into a PHP Object. We then check if the user has submited their answer for the poll or are we just loading the poll.

// Load the data from the file
$pollData = file_get_contents("poll-data.json");
        
// Turn it into an Object
$pollData = json_decode($pollData);

If the user has submitted their answer we loop through the options and find the one they voted for. Once we find it we take the current value of it and add one. We then transfer the results back to json string using json encode, and save it back to the poll-data.json file.


// Did the user post their answer?
if(isset($_POST['poll_value'])){
            
    // They did lets loop through our options
    foreach ($pollData->options as $key => $value) {
        // Here is the option they picked + 1 to it
        if($key == $_POST['poll_value']){
            $pollData->options->{$key} = intval($value) + 1;
        }
    }
            
    // Now save the updated data back to the file
    $dataFile = fopen('poll-data.json', 'w');
            
    // Here we convert back to jSON using json_encode
    fwrite($dataFile, json_encode($pollData));
    fclose($dataFile);

}

If we put it all together we should get the following.

<?php
    
// Make sure our poll data file exists...
if (file_exists('poll-data.json')) {
    
    // Load the data from the file
    $pollData = file_get_contents("poll-data.json");
        
    // Turn it into an Object
    $pollData = json_decode($pollData);
    
    // Did the user post their answer?
    if(isset($_POST['poll_value'])){
            
        // They did lets loop through our options
        foreach ($pollData->options as $key => $value) {    
                
                // Here is the option they picked + 1 to it
                if($key == $_POST['poll_value']){
                    $pollData->options->{$key} = intval($value) + 1;
                }
            }
            
            // Now save the updated data back to the file
            $dataFile = fopen('poll-data.json', 'w');
            
            // Here we convert back to jSON using json_encode
            fwrite($dataFile, json_encode($pollData));
            fclose($dataFile);

        }

    }else{
    
        // The data file was missing, stop everything!
        echo 'Missing poll-data.json file.';
        die;
    }

?>
<form method="post">
<div class="poll">
<h3><?=$pollData->question?></h3>
<ul>
<?php foreach($pollData->options as $key => $value){ ?>
<li>
<?php if(!isset($_POST['poll_value'])){ ?>
<input name="poll_value" type="radio" value="<?=$key?>" />
<?php }else{ ?>
<div class="result"><?=$value?></div>
<?php } ?>
<?=$key?></li>
<?php } ?>
</ul>
<?php if(!isset($_POST['poll_value'])){ ?>
<input type="submit" value="Submit" />
<?php } ?>
</div>
</form>

Lets just apply a little bit of CSS to make things pretty.

    @import url('http://fonts.googleapis.com/css?family=Open+Sans:400,300,600');
    body {
      font-family: 'Open Sans', sans-serif;
      font-weight: 400;
      background-color: #e4edf4;
      color: #53626E;
    }

    .poll {
      width: 300px;
      height: 400px;
      position: absolute;
      left: 50%;
      top: 50%;
      margin: -200px 0 0 -150px;
      border: #bfccd6 3px solid;
      padding: 20px 40px 20px 40px;
      -moz-box-sizing: border-box;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      border-radius: 4px;
      background-color: #FFF;
    }
    .poll h3 {
      margin: 20px 0 10px 0;
    }
    .poll ul, .poll li {
      list-style: none;
      margin: 0;
      padding: 0;
    }
    .poll li {
      padding: 10px 0 10px 0;
    }
    .poll input[type="radio"] {
      margin: 0 10px 0 0;
    }
    .poll input[type="submit"] {
      margin: 20px 0 0 0;
      background-color: #53626E;
      color: #FFF;
      border: 0;
      width: 100%;
      height: 40px;
      font-size: 10pt;
      border-radius: 4px;
    }
    .poll .result {
        display:inline-block;
        background-color:#EEE;
        font-size: 10pt;
        font-weight: 600;
        padding: 5px 15px 5px 15px;
        border-radius: 4px;
        float: right;
    }

That’s it! It’s all pretty straight forward. Below is a demo of the front end option of the poll. It will not actually work since the PHP side of things isn’t hooked up to the demo. Download the source files here.