Mimesis

Voting Poll

This snippet shows you how to create a simple yes/no voting poll on your site.

STRUCTURE

A form which accepts a yes or no input. Then through the use of some <div> tags styled with CSS we can graphically display the results.

CODE

<?php require_once('mimesis/Mimesis.php'); $cwd = realpath(dirname(__FILE__)); $tableName = 'votes'; $permissions = 0644; $rowLabel = str_replace('.', '_', $_SERVER['REMOTE_ADDR']); $mimesis = new Mimesis($cwd, $tableName, 'ts_' . $tableName, $permissions); if(isset($_POST['yes']) || isset($_POST['no'])){ if($mimesis->lock(1)){ if(false === @$mimesis->getRow($rowLabel, $rowLabel)){ if(isset($_POST['yes'])){ if(!$mimesis->insertRow(array($rowLabel => array('vote' => true)))) echo 'Unable to insert row into table.'; }else{ if(!$mimesis->insertRow(array($rowLabel => array('vote' => false)))) echo 'Unable to insert row into table.'; } }else{ echo 'Your IP address has already entered a vote.'; } if(!$mimesis->release()) echo 'Unable to release lock on table.'; } }else{ echo 'Unable to lock table.'; } } if($mimesis->tableExists()){ $poll = $mimesis->query(); $votes = array( 'yes' => 0, 'no' => 0 ); foreach($poll as $value){ if($value['vote']) $votes['yes']++; else $votes['no']++; } echo '<div style="width: 45%; border: solid 1px black;">'; echo '<div style="width: ' . ($votes['yes'] / count($poll) * 100) . '%; background-color: #00ff00;">'; echo $votes['yes']; echo '</div>'; echo '<div style="width: ' . ($votes['no'] / count($poll) * 100) . '%; background-color: #ff0000;">'; echo $votes['no']; echo '</div>'; echo '</div>'; }else{ echo 'No votes cast.'; } echo '<form method="POST" action="' . basename(__FILE__) . '">'; echo '<p><input type="radio" name="yes" CHECKED> Yes</p>'; echo '<p><input type="radio" name="no"> No</p>'; echo '<input type="submit">'; echo '</form>'; ?>

KEY CONCEPTS

Some of the important things to keep in mind when viewing this code are the following: