Simple Poll script with PHP and MySQL


This tutorial will demonstrate how to make a basic poll using PHP, and store the results in MySQL
DEMO: HERE

<?php
// mysql_connect (.......), mysql_select_db(........)

 //Creates polls SQL table automatically
mysql_query('CREATE TABLE IF NOT EXISTS `tutorialspots_polls` (
  `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 tutorialspots_polls 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 tutorialspots_polls(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 tutorialspots_polls WHERE answer = '$answer' AND question = '$question'");    
	$_result.="<li>".stripslashes($answer)."-----<strong style=\"color:red;\">".mysql_num_rows($sql)."</strong></li>";
}

echo("Results:<br /><br /><ul>$_result</ul>");    
}
?>

Leave a Reply