Database Articles

  Home arrow Database Articles arrow Page 3 - Adding a Poll to Your Web Site
DATABASE ARTICLES

Adding a Poll to Your Web Site
By: Codewalkers
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 203
    2005-06-29

    Table of Contents:
  • Adding a Poll to Your Web Site
  • Setting the Stage
  • Creating the Form
  • The Complete showvotes.php
  • Expanding the Poll
  • Polling Accuracy

  •  
     

    SEARCH CODEWALKERS

    Adding a Poll to Your Web Site - Creating the Form


    (Page 3 of 6 )

    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 
    "&lt;html&gt;\n";
    print 
    "&lt;head&gt;\n";
    print 
    "&lt;title&gt;Grand Old Opera Poll&lt;/title&gt;\n";
    print 
    "&lt;/head&gt;\n";
    print 
    "&lt;body&gt;\n";
    print 
    "&lt;form action=\"showvotes.php\" method=\"post\"&gt;\n";
    print 
    "&lt;p&gt;Which of these activities do you most enjoy?&lt;/p&gt;\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 
    "&lt;input type=\"radio\" name=\"vote\" value=" $row['choice'] . "&gt;"$row['activity'] . "&lt;br /&gt;\n";
      }
    }
    print 
    "&lt;input type=\"submit\" value=\"vote\"&gt;\n";
    print 
    "&lt;/form&gt;\n";
    print 
    "&lt;p&gt;&lt;a href=\"showvotes.php\"&gt;See vote totals&lt;/a&gt;&lt;/p&gt;\n";
    print 
    "&lt;/body&gt;\n";
    print 
    "&lt;/html&gt;\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.

    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']) &amp;&ampctype_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']) &amp;&amp$_POST['vote'] &gt&amp;&amp$_POST['vote'] &lt;= $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 
    "&lt;table&gt;\n";
      print 
    "&lt;tr&gt;&lt;th&gt;Activity&lt;/th&gt;\n";
      print 
    "&lt;th colspan=\"2\" align=\"center\"&gt;Votes&lt;/th&gt;&lt;/tr&gt;\n";
      while(
    $row mysql_fetch_array($result)) {
        print 
    "&lt;tr&gt;&lt;td&gt;" $row['activity'] . "&lt;/td&gt;\n";
        print 
    "&lt;td align=\"right\"&gt;" $row[1] . "&lt;/td&gt;\n";
        if(
    $sum) {
          
    $percent round($row['votes'] * 100 $sum);
          print 
    "&lt;/tr&gt;\n&lt;tr&gt;&lt;td&gt;";
          print 
    "&lt;img src=\"bargraph.php?pct=$percent\"&gt;&lt;/td&gt;\n";
          print 
    "&lt;td align=\"right\"&gt;" $percent "%&lt;/td&gt;\n";
        }
        print 
    "&lt;/tr&gt;\n";
      }
      print 
    "&lt;/table&gt;\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.

    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($im255255255); // white
    $fg imagecolorallocate($im25500); // red
    imagefilledrectangle($im00$_GET['pct'], $height$fg);
    imagerectangle($im00$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.

    More Database Articles Articles
    More By Codewalkers

    blog comments powered by Disqus

    DATABASE ARTICLES ARTICLES

    - MariaDB, a MySQL Alternative, Opens Foundati...
    - Oracle Supporting HP Itanium Again, Finally
    - Completing a Book Inventory Management System
    - Uploading Images for a Book Inventory Manage...
    - Finishing the Add Book Story for a Book Inve...
    - Integration Testing for a Book Inventory Man...
    - User Stories for a Book Inventory Management...
    - Unit Testing a Book Inventory Management Sys...
    - Testing a Book Inventory Management System
    - Implementing Models for a Book Inventory Man...
    - Book Inventory Application: Publishers and B...
    - Handling Publishers in a Book Inventory Mana...
    - Publisher Administration for Book Inventory ...
    - Book Inventory Management
    - Using the SQL Reference Manual

    Developer Shed Affiliates

     



    © 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap