PHP Poll
PHP Poll
// sanitization of input
function escape_data($data){
global $dbhandler;
$data=htmlentities($data);
if(ini_get('magic_quotes_gpc')){
$data=stripslashes($data);
}
return mysql_real_escape_string(trim($data),$dbhandler);
}
// poll in use
$activepollid="1";
// show results
if(isset($_GET['showresults'])){
$usershow=escape_data($_GET['showresults']);
if($usershow=="on"){
$pollinfo=mysql_fetch_array(mysql_query("SELECT * FROM poll_main WHERE
id='$activepollid'"),MYSQL_ASSOC);
echo "<h3>$pollinfo[question]</h3>
<div><table cellpadding=\"5\" cellspacing=\"0\" border=\"1\"><caption>Results</caption>
<tr><th>Options</th><th>Votes</th></tr>";
echo "</table></div>";
echo "<p><a href='".$_SERVER['PHP_SELF']."'>Go Back</a></p>";
1
exit(0);
}
}
// submit vote
if(isset($_POST['choice'])){
$userchoice=escape_data($_POST['choice']);
if(!mysql_query("UPDATE poll_choice SET votes=votes+1 WHERE pollid='$activepollid' AND
id='$userchoice'")){
echo "<p>Error: Vote was not commited.</p>";
} else {
echo "<p><b>Thank you!</b></p>";
}
echo "<p><a href='?showresults=on'>See Results</a></p>";
echo "<p><a href='".$_SERVER['PHP_SELF']."'>Go Back</a></p>";
exit(0);
}
// show poll
$pollinfo=mysql_fetch_array(mysql_query("SELECT * FROM poll_main WHERE
id='$activepollid'"),MYSQL_ASSOC);
$form=$_SERVER['PHP_SELF'];
echo "<h3>$pollinfo[question]</h3>
<div><form method='post' action='$form'>";
$choicedata=mysql_query("SELECT * FROM poll_choice WHERE pollid='$activepollid' ORDER BY id
ASC");
while($choiceinfo=mysql_fetch_array($choicedata,MYSQL_ASSOC)){
echo "<input type='radio' name='choice' value='$choiceinfo[id]'
id='choice".$choiceinfo["id"]."'/><label
for='choice".$choiceinfo["id"]."'>$choiceinfo[text]</label><br />";
}
echo "<input type='submit' value='Cast Your Vote' class='button' /></form>";
echo "<p><a href='?showresults=on'>See Results</a></p></div>";
?>
----------------------------------------------------------------------
--
-- Table structure for table `poll_main`
--
--
-- Dumping data for table `poll_main`
--
--
-- Table structure for table `poll_choice`
--
2
`text` varchar(200) NOT NULL default '',
`votes` int(11) NOT NULL default '0',
PRIMARY KEY (`id`,`pollid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
--
-- Dumping data for table `poll_choice`
--
The nice thing about this poll is that you can have as many options as you like. Just insert the appropriate
number of rows into poll_choice table. You can retain old polls inside the database and create new ones
by adding them to poll_main table. After you create a new poll you have to change only the value for the
variable $activepollid at the beginning of the script and your poll is ready to go public.