results.php
<?php
// get the poll data
$dat_file = 'poll.dat';
$poll_data = unserialize(file_get_contents($dat_file));
// define question, options, and votes
$question = $poll_data['question'];
$options = $poll_data['options'];
$votes = $poll_data['votes'];
// count the number of options and votes
$total_options = count($options);
$total_votes = array_sum($votes);
// echo out the poll question
echo $question."<br /><br />\n";
// loop through each option
for($x=0; $x<$total_options; $x++) {
// calculate percentage if the number of votes is NOT zero
// otherwise, the percentage is zero
$percentage = ($total_votes != 0) ?
number_format($votes[$x] * 100 / $total_votes) : 0;
// echo out the option
echo $options[$x].'<br />';
// echo out the number of votes and percentage
echo $votes[$x].' votes - '.$percentage."%<br /><br />\n";
}
echo 'Total votes: '.$total_votes.'<br />';
?>
index.php
<?php
$self = $_SERVER['PHP_SELF'];
// get the poll data
$dat_file = 'poll.dat';
$poll_data = unserialize(file_get_contents($dat_file));
// define question, options, and votes
$question = $poll_data['question'];
$options = $poll_data['options'];
$votes = $poll_data['votes'];
// count the number of options and votes
$total_options = count($options);
$total_votes = array_sum($votes);
// if the vote form has not been submitted
if(!isset($_POST['vote'])) {
?>
<form action="<?php echo $self; ?>" method="post">
<?php
echo $question."<br /><br />\n";
for($x=0; $x<$total_options; $x++) {
echo '<input type="radio" name="option" value="'.$x.'"';
if($x == 0) echo ' checked';
echo ' /> '.$options[$x]."<br />\n";
}
?>
<br />
<input type="submit" name="vote" value="Vote" />
<input type="submit" name="vote" value="View" />
</form>
<?php
} else {
// if the vote form has been submitted
if($_POST['vote'] == 'Vote') {
// if the user clicked 'Vote'
$poll_data['votes'][$_POST['option']]++;
$handle = fopen($dat_file,'w');
fwrite($handle,serialize($poll_data));
fclose($handle);
require('results.php');
} else {
// else, the user clicked 'View'
require('results.php');
}
}
?>
setup.php
<?php
$poll = array(
'question' => 'This is a poll question?',
'options' => array('Yes', 'No', 'Huh?'),
'votes' => array(0, 0, 0),
);
$dat_file = 'poll.dat';
$poll_data = serialize($poll);
$handle = fopen($dat_file,'w+');
fwrite($handle,$poll_data);
fclose($handle);
?>
poll.dat CHMOD to 777
Edited by ennio, 21 June 2005 - 06:21 PM.
