PHP Poll Script
In the code below, we show half the code needed for a website poll. The rest—in which the vote gets added to the database table—is in the file add-poll-vote-to-database.php, explained in Script to Add Poll Vote to Database.
According to Polls & Surveys, "Easier [definition] - A survey, sometimes called a poll, is a study of what people think or believe about a topic or question. Surveys are usually done by questionnaire, interview, or observation. Harder [definition] - Public opinion polls are useful in tracing people's views on important social issues. Polls are used to assess people's preferences in political races, and the results are used to predict election results. Surveys are often employed in marketing and advertising research to measure and predict consumer's reaction to products."
We use ip tracking to validate/filter votes. Many others use ips as well, but there are others who use sessions. In the website tutorial called Build your own Survey/Poll Application, the author says "Session variables work by sending you an ID as a cookie. If you have cookies disabled then the session variable won't work, and you can vote over and over again! You might want to check that cookies are enabled in the browser." This would mean either people vote over and over and the poll is useless or you tell them to turn on cookies and they don't and the poll is useless, or you detect cookies being off and you keep them out of your poll as a result. We didn't particularly care for these options, so we went with ip address storing, the other main form of vote validation. People might have rotating (dynamic) ip addresses assigned by their ISPs, but most do not, and most of those that do will change monthly, but for the worst case scenario of hourly ip change (it could also change daily), we're still dealing with someone so incredibly motivated to multi-vote that he comes back hourly to vote—which he would have to do a LOT to significantly affect vote tallies. This is not realistic, to say the least! Even though people with the same ip (i.e., siblings) may wish to vote, the likelihood is very remote, and nothing is stopping one of them from using the home computer while another uses a work computer. Many houses have several computers, which means an avid voter can triple (or worse) his vote with ease if the cookies and sessions method is active. The ip storing method stops this. With either ip storing or cookies and sessions, voters can make use of friends' computers or work computers as a multi-vote workaround strategy. Summary: we believe the above info shows ip storing is superior to the cookies and sessions method for insuring less corrupted vote tallies.
The article just cited has a pretty nice website devoted to teaching PHP, and polls are just one of his lessons. This author relies on cookies and sessons (probably due to ease of use more than overall effectiveness). We do not. Anyway, he uses a multi-question MySQL database table where he stores questions, answers, tallies, etc. We use a single question MySQL database table where only tallies are stored—plus we store ip addresses. We compare voters' ip addresses with the stored list, and repeaters are prevented from registering a vote.
The COUNT(*) function returns the number of records in a table. It turns out this is the perfect way to find out if a table is empty when you have a situation where lack of data in a table will cause errors in comparison codes. We create a table on the fly and immediately put in zeros for data so the calculations we need can use these rather than choking on "no data" or errors. Defining default values during table creation allow values to be specified for each column to be used when a value is not specifically defined when rows are inserted into to a database. The default values do not actually self-insert into the records just because you define them. The table is empty. The COUNT(*) function, however, helps out here by allowing us to detect an empty table and add data then, during table creation, and only then, since you do not want the initially needed zero (or other defaults) values to be inserted once the table is no longer empty!
Now—on to the script code:
After using the config.php file to get the necessary magic words for db connection, we define a MySQL database poll table to hold the total number of votes for each of the 3 possible answers, and an ips table to hold the ips of all voters. Note that defining default values still leaves the table empty. MySQL has CREATE and INSERT, but not CREATEINSERT. The reason the poll table gets no auto-increment is simple: there is only 1 record! If you're motivated to run lots of polls, you can easily define tables in which there are record fields not just for tallies for each response, but also question text, answers text, and number of possible responses. If you prefer the simplicity of having questions and possible responses exist only in the HTML voting FORM and the database table having only response tallies, our code will suffice. If there are more than 3 possible responses, expand the number of fields accordingly.
Next, if the table is empty, the defaults are actually entered into the table. Then, whether the table has just been zero-loaded or not, the values are SELECTed and stuck into $numA, $numB and $numC. Then we start up some JavaScript and the values just found are put into the variables numA, numB and numC. These values are totaled, and this total is divided into the 3 values to get percentages as well as image widths. Note the use of the round() function to convert the percents into integers.
Then the 3 calculated widths are used as width attributes of the image blue.png, which is 20 pixels tall and 1 pixel wide, but totally willing to be convinced to be any other width so as to make the job of showing a horizontal bar graph much easier. All major browsers allow a div with a colored background to be used as the bar, but then the label ends up on the next line. IE and some others allows a span with a colored background to be used as the bar, but Firefox will have none of it, so we used the streeeeeeechable image method. Note that if there are NO votes yet, a message warns the user.
The poll question here is Do you think J.Lo has a great backside? Well—it's certainly an interesting subject, anyway! The answers are Yes, No, and Maybe. (Those voting no are either jealous, gay, or crazy.) Then there is a standard radio button based response input form with a submit button.
This file is named: PHP-poll.php
<html>
<head>
<title>PHP Poll</title>
<meta name="description" content="PHP Poll">
<meta name="keywords" content="PHP Poll,PHP Poll,php,poll,mysql,dhtml,DHTML">
</head>
<body>
<?php
include_once"config.php";
$sql = "CREATE TABLE IF NOT EXISTS poll (
id int(4) NOT NULL default '1',
numA int(4) NOT NULL default '0',
numB int(4) NOT NULL default '0',
numC int(4) NOT NULL default '0',
PRIMARY KEY (id)
)";
mysql_query($sql);
$sql = "CREATE TABLE IF NOT EXISTS ips (
id int(11) NOT NULL auto_increment,
ip varchar(15) NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=1";
mysql_query($sql);
$countrecords = mysql_result(mysql_query('SELECT COUNT(*) FROM poll'), 0);
if(!$countrecords){mysql_query("INSERT INTO poll (id, numA, numB, numC)
VALUES('1','0','0','0')") or die(mysql_error());}
$res = mysql_query("SELECT * FROM poll") or die(mysql_error());
while ($row = mysql_fetch_array($res)){
$numA = $row['numA'];
$numB = $row['numB'];
$numC = $row['numC'];}
mysql_close();
?>
<center><h1>PHP Poll</h1></center>
<div style='position:absolute;top:53px;left:320px;width:600px;'>
<script language="javascript">
var numA = <?php echo $numA; ?>;
var numB = <?php echo $numB; ?>;
var numC = <?php echo $numC; ?>;
var total = numA + numB + numC;
if(numA>0){var percentnumA = ((numA * 100) / total);
percentnumA = Math.round(percentnumA);var widthnumA = percentnumA * 2;}else{var widthnumA=1; var percentnumA=0;}
if(numB>0){var percentnumB = ((numB * 100) / total);
percentnumB = Math.round(percentnumB);var widthnumB = percentnumB * 2;}else{var widthnumB=1; var percentnumB=0;}
if(numC>0){var percentnumC = ((numC * 100) / total);
percentnumC = Math.round(percentnumC);var widthnumC = percentnumC * 2;}else{var widthnumC=1; var percentnumC=0;}
if(total>0){document.write("<div style='position:absolute;top:253px;left:0px;width:300px;height:150px;border:1px solid blue'><BR>");
document.write("<IMG SRC='blue.png' width="+widthnumA+" HEIGHT=20 BORDER=0> "+percentnumA+"% Yes<BR><BR>");
document.write("<IMG SRC='blue.png' width="+widthnumB+" HEIGHT=20 BORDER=0> "+percentnumB+"% No<BR><BR>");
document.write("<IMG SRC='blue.png' width="+widthnumC+" HEIGHT=20 BORDER=0> "+percentnumC+"% Maybe<BR><BR>");
document.write("</div>");}else{alert("No votes yet.");}
</script>
<FORM NAME ="form" METHOD ="GET" ACTION ="add-poll-vote-to-database.php"><BR>
Do you think J.Lo has a great backside?<BR>
<P>
<INPUT TYPE = 'Radio' Name ='answer' value= 'choiceA' unchecked> Yes<BR>
<INPUT TYPE = 'Radio' Name ='answer' value= 'choiceB' unchecked> No<BR>
<INPUT TYPE = 'Radio' Name ='answer' value= 'choiceC' unchecked> Maybe<BR><BR>
<INPUT TYPE = "Submit" Name = "Submit" VALUE = "Vote">
</P>
</FORM>
</div>
</body>
</html>