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:
- We use the IP address as provided by the $_SERVER['REMOTE_ADDR'] to create the row labels for our entries
- So long as $_POST['yes'] is set it is automatically assumed to be a yes vote, if it is not set then vote will always be a no
- We test to see if an IP address already exists in our table by checking for its label (this means this person, or at least their ip address, has already cast a vote)
- To determine the percentages of votes we count the number of yes votes and number of no votes and divided them by the total votes
- Permission 0644 is used in this example because on the 110mb.com server 0644 corresponds to the most accessible php script permissions
- The lock performed here is a polling lock, which means it won't stop trying until it acquires a lock on the table OR the script times out
- We display errors in every possible location where one might occur