FireFox! The PHP Forum Loans and Credit
Panama Web Design for Hire Free Insurance Quotes!
Web Hosting Advertise Here $10 a Month Designer Children
Never Pay Taxes Again HGH Domain name registration
Web Hosting and Dedicated Servers Insurance Affordable web-hosting


HomeWatched TopicsRegisterSearchDirectory
FAQMemberlistUsergroupsLog inStoresItemsBank
Google

Reply to topic Page 1 of 1
Adding a Poll to Your Web Site
Message  

Reply with quote
Post Adding a Poll to Your Web Site 
Setting the Stage
Let's suppose that Nashville's less known but more pretentious music hall, the Grand Old Opera, has decided to add a poll to their website to measure their visitors' preferences.

The first step is to create the database. For now we will create one table, the poll answers. Later I'll discuss ways to expand the database to handle a multi-question survey or a series of polls.

The following code will create the database and table, insert the choices, and grant permissions for the user.

CREATE DATABASE polls;
USE polls;
CREATE TABLE poll_answers
  (choice INT NOT NULL PRIMARY KEY,
  activity VARCHAR(35) NOT NULL, votes INT DEFAULT 0);
INSERT INTO poll_answers(choice, activity, votes) VALUES(1, "Going to the opera", 4),
  (2, "Listening to opera music on CD", 2),
  (3, "Getting bitten by a ferret", 14);
GRANT SELECT, UPDATE ON polls.* TO user IDENTIFIED BY 'pass';  


This creates a database named polls, and a table named poll_answers. This table has three fields: choice, a number representing the choice; activity, a text description of the choice; and votes, the number of votes this choice has received. Later I'll explain how to expand the database to handle multiple polls.

Normally we would initialize the votes field to zero for each choice, but for this tutorial I am using nonzero values to simulate a history of previous votes.

The GRANT statement lets the user with name 'user' and password 'pass' select and/or update rows from the database. In a live environment, you'll want to choose a username and password that would not be so easy for a malicious user to guess.

Source: http://codewalkers.com/tutorials/92/2.html

View user's profile Send private message

Reply with quote
Post  
Creating the Form
Next we create the form itself. Below is a complete voting form Which I've named poll.php.

<?php
$host = 'localhost';
$user = 'user';
$pass = 'pass';
$db = 'polls';
print "<html>\n";
print "<head>\n";
print "<title>Grand Old Opera Poll</title>\n";
print "</head>\n";
print "<body>\n";
print "<form action=\"showvotes.php\" method=\"post\">\n";
print "<p>Which of these activities do you most enjoy?</p>\n";
$dbcon = mysql_connect($host, $user, $pass)
  or die('Unable to connect to server ' . $host);
mysql_select_db($db) or die('Unable to find database ' . $db);
$form_query = 'SELECT * FROM poll_answers';
if($result = mysql_query($form_query)) {
  while($row = mysql_fetch_array($result)) {
    print "<input type=\"radio\" name=\"vote\" value=" . $row['choice'] . ">". $row['activity'] . "<br />\n";
  }
}
print "<input type=\"submit\" value=\"vote\">\n";
print "</form>\n";
print "<p><a href=\"showvotes.php\">See vote totals</a></p>\n";
print "</body>\n";
print "</html>\n";
?>  


This php code creates an HTML form with one input field named vote. The three choices are read from the database into the form's vote field.

Source: http://codewalkers.com/tutorials/92/3.html

View user's profile Send private message

Reply with quote
Post  
Tabulating the Results
Next we create the PHP routines to tabulate the votes. These will go into the file showvotes.php. First I am going to discuss the SQL queries that make up the core of showvotes.php, then I will display the script in its entirety.

The first step is to add the current vote to the total for the appropriate answer. Since the form will allow users to see the vote totals without voting themselves, we must first check to see if the variable $_POST['vote'] exists. If it is not set, we won't want to add a vote.

<?php
if(isset($_POST['vote']) && ctype_digit($_POST['vote'])) {
  $query = 'UPDATE poll_answers SET votes=votes+1';
  $query .= ' WHERE choice=' . $_POST['vote'];
  $result = mysql_query($query);
}
?>  


In addition to checking whether the variable exists, we need to be sure that it is numeric. Although our form contains only numeric values, a malicious user could create a form (even on a different web domain) that points to showvotes.php and sends a bad value, or even an additional query, to MySQL. The function ctype_digit() checks the variable to see if every character is a decimal digit. If $_POST['vote'] contains any non-numeric characters, the update query will not be executed.

This provides some security but is not the most efficient. A more robust way to check the validity of the data would be to query the database to get the actual number of choices, assign this total to a variable, say $count, and then change the if() statement to:

<?php
if(isset($_POST['vote']) && $_POST['vote'] > 0 && $_POST['vote'] <= $count) {
...
?>  


This would prevent the user from sending the value '9' to MySQL if the poll had 8 choices. Using ctype_digit(), the query would still run but would not update any rows.

Once we've added the vote we will need to retrieve both the number of votes for each choice and the total number of votes cast. We'll get the sum of the vote totals from the database first.

<?php
$num_votes_query = 'SELECT SUM(votes) AS sumvotes';
$num_votes_query .= ' FROM poll_answers';
if ($result = mysql_query($num_votes_query)) {
  $row = mysql_fetch_array($result);
  $sum = $row['sumvotes'];
}
?>  


It is possible to eliminate the query to obtain the sum of the votes, run just the query to get the votes for each choice and calculate the overall total using PHP. That would make less work for the database server, but would also require more processing and more data storage for the PHP engine, as well as more coding. For your own polls you can use either method; just be aware of the tradeoffs involved.

Finally, we run the query to get the choices and vote totals. Because we already know the total number of votes, we can calculate the percentage for each choice as we read its row.

<?php
$totals_query = 'SELECT activity, votes FROM poll_answers ';
if ($result = mysql_query($totals_query)) {
  print "<table>\n";
  print "<tr><th>Activity</th>\n";
  print "<th colspan=\"2\" align=\"center\">Votes</th></tr>\n";
  while($row = mysql_fetch_array($result)) {
    print "<tr><td>" . $row['activity'] . "</td>\n";
    print "<td align=\"right\">" . $row[1] . "</td>\n";
    if($sum) {
      $percent = round($row['votes'] * 100 / $sum);
      print "</tr>\n<tr><td>";
      print "<img src=\"bargraph.php?pct=$percent\"></td>\n";
      print "<td align=\"right\">" . $percent . "%</td>\n";
    }
    print "</tr>\n";
  }
  print "</table>\n";
}
?>  


The results are outputted into a table. Each row from the database becomes two rows in the html table. As each choice is read from the database, the description and number of votes are inserted into the table. Then the bargraph and percentage are added below.

The if($sum) line checks to see whether the total number of votes is greater than zero. Without this check, we would have a divide by zero error displayed in our results. That's usually not desirable, so, if no vote have been cast, we won't calculate the percentages.

Source: http://codewalkers.com/tutorials/92/4.html

View user's profile Send private message

Reply with quote
Post  
Graphing the Results
showvotes.php calls a second PHP script, bargraph.php, which draws a bar image with a length equal to the percentage of votes for each selection. You'll need the GD library installed to create the image. This is one way to draw the graph. If the GD library is not available or if you want to conserve cycles on a busy server, other options are available, although they are beyond the scope of this tutorial.

The GD library enables us to create images on the fly, so we don't have to store 100 files of different bar lengths to cover all the possible percentages. PHP's GD functions make on-the-fly image creation a snap.

<?php
$height = 10;
$width = 100;
$im = imagecreate($width, $height);
$bg = imagecolorallocate($im, 255, 255, 255); // white
$fg = imagecolorallocate($im, 255, 0, 0); // red
imagefilledrectangle($im, 0, 0, $_GET['pct'], $height, $fg);
imagerectangle($im, 0, 0, $width, $height, $bg);
header("Content-type: image/png");
imagepng($im);
imagedestroy($im);
?>  


First we need to set aside a block of memory for the image. This we do with the imagecreate() function. Next, we define the colors for the image, with imagecolorallocate(). For this image we only need two colors, one for the bar and one for the background.

The function imagefilledrectangle() draws a filled rectangle in the image. We will create two filled rectangles, one for the bar showing the percentage, and one for the remainder of the image.

To this point, all our image drawing has been done in memory. Now we are ready to output it to the browser.The GD library supports several image formats, including jpeg, gif, png, tiff, and wbmp, as well as GD's own graphics format. Images can be copied to a browser or to a file.

When outputting to a browser, the header() function must be the PHP script's first line of output.

In this example, we are sending a png image to a browser. The imagepng() function sends a copy of the image to the browser. Once this is done, we can delete the image from memory using imagedestroy().

Now that we've got our database, our form, our queries and our bar graph, all the pieces are in place for our poll.

Source: http://codewalkers.com/tutorials/92/5.html

View user's profile Send private message

Reply with quote
Post  
The Complete showvotes.php
Below is the complete code to showvotes.php. The other two files, poll.php and bargraph.php, have already appeared previously in their entirety.

<?php
$host = 'localhost';
$user = 'user';
$pass = 'pass';
$db = 'polls';
print "<html>\n";
print "<head>\n";
print "<title>Vote totals</title>\n";
print "</head>\n";
print "<body>\n";
$dbcon = mysql_connect($host, $user, $pass)
  or die('Unable to connect to server ' . $host);
mysql_select_db($db) or die('Unable to find database ' . $db);
if(isset($_POST['vote']) && ctype_digit($_POST['vote'])) {
  $query = 'UPDATE poll_answers SET votes=votes+1
  WHERE choice=' . $_POST['vote'];
  $result = mysql_query($query);
}
$num_votes_query = 'SELECT SUM(votes) AS sumvotes
FROM poll_answers';
$num_votes_query .= ' WHERE poll_num=1';
if ($result = mysql_query($num_votes_query)) {
  $row = mysql_fetch_array($result);
  $sum = $row['sumvotes'];
}
$totals_query = 'SELECT activity, votes FROM poll_answers ';

if ($result = mysql_query($totals_query)) {
  print "<table>\n";
  print "<tr><th>Activity</th><th>Votes</th></tr>\n";
  while($row = mysql_fetch_array($result)) {
    print "<tr><td>" . $row['activity'] . "</td>\n";
    print "<td align=\”right\”>" . $row['votes'] . "</td></tr>\n";
    if($sum) {
      $percent = round($row['votes'] * 100 / $sum);
      print "<tr><td><img src=\”bargraph.php?pct=$percent\”></td>\n";
      print "<td align=\”right\”>" . $percent . "%</td></tr>\n";
    }

  }
  print "</table>\n";
}
print "</body>\n";
print "</html>\n";
?>  

Source: http://codewalkers.com/tutorials/92/6.html

View user's profile Send private message

Reply with quote
Post  
Expanding the Poll
What if you want to create a new poll each week, or a 25-question survey, or even a trivia quiz? Simple! Create a second table, poll_questions, to hold all the questions. Add an index to poll_answers to reference the question number.

The SQL for poll_questions might look like this:

CREATE TABLE poll_questions
(poll_num INT NOT NULL PRIMARY KEY,
 question VARCHAR(35) NOT NULL)  


And the new poll_answers:

CREATE TABLE poll_answers
(poll_num INT NOT NULL, choice INT NOT NULL,
 activity VARCHAR(35) NOT NULL, votes INT DEFAULT 0,
 PRIMARY KEY (poll_num, choice))  


You could also add date fields to poll_questions to set a starting and ending date for each question to be displayed. If you're designing a quiz, you could add a field to poll_questions to indicate which answer is correct.

Source: http://codewalkers.com/tutorials/92/7.html

View user's profile Send private message

Reply with quote
Post  
Polling Accuracy
It's a fact: Web poll results are not an accurate reflection of the population at large. First, many people choose not to participate in polls, and there's nothing you can do to change that. Second, some people will try to skew the results by casting multiple votes. There are ways to limit users to one vote, but determined users can get around all of them.

You can set a cookie whenever a user casts a vote, but there are two problems with this: 1) Some users disable cookies, and 2) Some users regularly clear their cookies. So some people will be unable to vote, while others will be able to vote more than once after clearing their cookies.

You could also log the IP address of each visitor, and allow only one vote from each address. Once again, there are two problems: 1) Some users share a machine with other users, or have access only through public machines, and 2) Some users have access through multiple IPs, for example, at home and at work. Users with dialup connections may be assigned a different IP address each time they connect. Once again, some users will not be able to participate, and others will still be able to vote more than once.

You might force users to register their email address and log in before voting. Then you could add another table to the database to track which polls each user has voted. Again, there are two problems: 1) Some users will not want to bother with setting up an account just to vote in a poll or will not want to give out their email address, and 2) Some users will use multiple email addresses to beat the system and vote more than once.

There's no sure way to keep a determined user from skewing the poll results. So take polls for what they are worth and don't put too much stock in their results. Done right, a poll can be an easy way to let visitors interact with your site, and it's usually more fun than getting bitten by a ferret.


Source: http://codewalkers.com/tutorials/92/8.html

View user's profile Send private message
Display posts from previous:
Reply to topic Page 1 of 1
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
  



Google

FireFox! The PHP Forum Loans and Credit
Panama Web Design for Hire Free Insurance Quotes!
Web Hosting Advertise Here $10 a Month Designer Children
Never Pay Taxes Again HGH Domain name registration
Web Hosting and Dedicated Servers Insurance Affordable web-hosting


Web Design by PlatinumShore.com & Web Hosting by TradeWebHosting.com