PHP Simple Poll Script

Just include this piece of code in your site, if you find it useful

/**
 * Webarto.com - Simple PHP & MySQL Polling Script
 */

//Creates polls SQL table automatically
mysql_query('CREATE TABLE IF NOT EXISTS `anketa` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `question` text NOT NULL,
  `answer` text NOT NULL,
  `ip` text NOT NULL,
  `unix` int(11) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;');


//Define question and answers
$question = "Do you like our website?";
$answers = array("I like it!",
"It is OK",
"Nothing special",
"I do not like it"
);

//Checking if voted already
$sql = mysql_query("SELECT * FROM anketa WHERE question = '$question' AND ip='".$_SERVER["REMOTE_ADDR"]."'");
(mysql_num_rows($sql) > 0) ? $voted = 1 : $voted = 0;

//Checking some conditions
if($_POST["question"] == $question && in_array($_POST["answer"],$answers) && $voted == 0){
	mysql_query("INSERT INTO anketa(question,answer,ip,unix) VALUES('$question','".$_POST["answer"]."','".$_SERVER["REMOTE_ADDR"]."','".time()."')");
	echo("<h4>You have successfully voted!</h4>");
	$voted = 1;
}

//Show the options or results, depending on voting status
if($voted == 0){

foreach($answers as $answer){
	$tmp.= '<input type="radio" name="answer" value="'.$answer.'" /> '.stripslashes($answer).'<br />'."\n";
}

echo('<form action="" method="post">
'.$question.'<br /><br />
'.$tmp.'
<input type="hidden" name="question" value="'.$question.'"/><br />
<input type="submit" value="Vote"/>
</form>');
}else{

foreach($answers as $answer){
	$sql = mysql_query("SELECT id FROM anketa WHERE answer = '$answer' AND question = '$question'");
	$rezultati.="<li>".stripslashes($answer)." <strong style=\"float:right;\">".mysql_num_rows($sql)."</strong></li>";
}

echo("Results:<br /><br /><ul>$rezultati</ul>");    
}
©2009-2011 Webarto • web design & development • Tuzla // Sarajevo // Beograd