PHP
  Home arrow PHP arrow Page 7 - Democracy, The PHP Way
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PHP

Democracy, The PHP Way
By: Vikram Vaswani, (c) Melonfire
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 22
    2001-04-16


    Table of Contents:
  • Democracy, The PHP Way
  • The Plan
  • Design View
  • Start Me Up
  • Vote Now, Or Forever Hold Your Peace
  • The Number Game
  • Down Memory Lane
  • Cookie-Cutter Code
  • Adding More...

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Democracy, The PHP Way - Down Memory Lane
    ( Page 7 of 9 )

    So that takes care of the mechanics of displaying a question, registering votes, and displaying totals. The next item to address is the stated requirement to be able to view previous polls. In this application, the script to accomplish this is called "archive.php".

    "archive.php" is extremely simple. It connects to the database, queries for a list of all available polls and votes, and then uses a "while" loop to iterate through the result set and display the final tally for each poll. Take a look:

    <html> <head> <basefont face="Arial"> </head> <body bgcolor="white"> <? // includes include("config.php"); include("common.php"); // connect and get a list of previous questions $connection = mysql_connect($hostname, $user, $pass) or die ("Unable to connect!"); $query = "SELECT question, response1, response2, response3, votes1, votes2, votes3, date from $table"; $result = mysql_db_query($database, $query, $connection) or die ("Could not execute query: $query. " . mysql_error()); // iterate through resultset while(list($question, $response1, $response2, $response3, $votes1, $votes2, $votes3, $date) = mysql_fetch_row($result)) { // calculate the total votes $total = $votes1 + $votes2 + $votes3; if ($total > 0) { // convert sub-totals into percentages $perc_votes1 = round(($votes1/$total)*100,2); $perc_votes2 = round(($votes2/$total)*100,2); $perc_votes3 = round(($votes3/$total)*100,2); } // no votes yet - can cause "division by zero" errors else { $perc_votes1 = $votes1; $perc_votes2 = $votes2; $perc_votes3 = $votes3; } // print a table with results echo "<table border=0 cellspacing=0 cellpadding=5>"; echo "<tr><td colspan=3><b>$question</b></td></tr>"; // and a graph echo "<tr><td>$response1</td><td> $votes1 ($perc_votes1%)</td><td rowspan=4 valign=top><img src=graph.php?votes1=$votes1&votes2=$votes2&votes3=$votes3 border=0></td></tr>"; echo "<tr><td>$response2</td><td> $votes2 ($perc_votes2%)</td></tr>"; echo "<tr><td>$response3</td><td> $votes3 ($perc_votes3%)</td></tr>"; echo "<tr><td><font size=-2>Posted on " . fixDate($date) . "</font></td><td><font size=-2>$total total votes</font></td></tr>"; echo "</table><p>"; } // close connection mysql_close($connection); ?> <p> <font size="-2"><a href="start.php">back to main page</a></font> </body> </html>

    In this case, I've checked that the total number of votes is greater than zero before calculating percentages, to avoid "division by zero" errors - this is the correction I mentioned a few pages back.

    Here's what it looks like:



    There's one more thing I'd like to do before leaving "archive.php" - modify it so that, in addition to displaying a complete list of previous polls and results, it also has the capability to display the results of any single, specified poll. This comes in handy on my first page, since it allows me to offer my users a couple of additional options before they cast their vote.

    <!-- from start.php --> <font size=-2><a href="archive.php?id=<? echo $id; ?>">view results</a></font>        <font size=-2><a href="archive.php">view past polls</a></font>

    If "archive.php" is called without any parameters, it should display the complete archive; if called with a specific $id identifier, it should only display results for that specific poll question.

    This is pretty easy to accomplish - I just need to inject the following code snippet into the script:

    <? // archive.php $query = "SELECT question, response1, response2, response3, votes1, votes2, votes3, date from $table"; // if a specific id is requested, modify query to only return that question if ($id) { $query .= " WHERE id = $id"; } $result = mysql_db_query($database, $query, $connection) or die ("Could not execute query: $query. " . mysql_error()); ?>


    This article copyright Melonfire 2001. All rights reserved.{mospagebreak title=One Picture, A Thousand Words} Both "archive.php" and "vote.php" rely on a dynamically-generated bar graph to spiff up the page design. And this dynamically-generated graph is created through the magic of PHP's image generation functions, as embodied in the file "graph.php".

    If you take a close look at the scripts above, you'll see that "graph.php" is always passed a few variables via the URL GET method; these variables represent the number of votes for each of the three available options. The function of "graph.php" thus becomes to calculate appropriate percentages for each of these options, and represent these percentages graphically. Let's take a look:

    <? // graph.php - generates a bar graph of votes using an existing, blank image // calculate the total $total = $votes1 + $votes2 + $votes3; if ($total > 0) { // convert sub-totals into percentages $perc_votes1 = round(($votes1/$total)*100,2); $perc_votes2 = round(($votes2/$total)*100,2); $perc_votes3 = round(($votes3/$total)*100,2); } // "division by zero" correction else { $perc_votes1 = $votes1; $perc_votes2 = $votes2; $perc_votes3 = $votes3; } // header Header("Content-Type: image/jpeg"); // set up image and colours $im = ImageCreateFromJPEG("graph.jpg"); $blue = ImageColorAllocate($im, 8, 63, 206); // fill with colour up to specific length // length of colour bar depends on percentage of votes ImageFilledRectangle($im, 0, 3, ($perc_votes1*2), 9, $blue); ImageFilledRectangle($im, 0, 34, ($perc_votes2*2), 40, $blue); ImageFilledRectangle($im, 0, 65, ($perc_votes3*2), 71, $blue); // output to browser ImageJPEG($im); ?>

    The first few lines are familiar - the conversion of absolute numbers into percentages.

    <? // calculate the total $total = $votes1 + $votes2 + $votes3; if ($total > 0) { // convert sub-totals into percentages $perc_votes1 = round(($votes1/$total)*100,2); $perc_votes2 = round(($votes2/$total)*100,2); $perc_votes3 = round(($votes3/$total)*100,2); } // "division by zero" correction else { $perc_votes1 = $votes1; $perc_votes2 = $votes2; $perc_votes3 = $votes3; } ?>

    Once that's done with, a header is sent and a base image, "graph.jpg", read into memory. This is the base image for all graphs to be generated, and it looks like this:



    The length of each empty bar in the image above is 200 pixels (100%). Now, based on the percentage values already generated, "graph.php" will fill each bar with a specified colour; the length of the fill is determined by the quantum of votes. For example, if a specific option receives 25% of the votes, the fill will be 50 pixels long (25% of 200).

    <? // fill with colour up to specific length // length of colour bar depends on percentage of votes ImageFilledRectangle($im, 0, 3, ($perc_votes1*2), 9, $blue); ImageFilledRectangle($im, 0, 34, ($perc_votes2*2), 40, $blue); ImageFilledRectangle($im, 0, 65, ($perc_votes3*2), 71, $blue); ?>

    Once the bars are filled, the image is sent to the browser for display.

    <? // output to browser ImageJPEG($im); ?>

    Here's an example of what it might look like.

    In case this didn't make any sense, you should take a look at the article entitled "Image Generation With PHP" at http://www.devshed.com/Server_Side/PHP/ImageGeneration/. And after you're done with that, come back here and experiment with displaying poll results in the form of a pie chart, rather than a bar graph. Go on - it isn't nearly as hard as it looks!

    This article copyright Melonfire 2001. All rights reserved.

     
     
    >>> More PHP Articles          >>> More By Vikram Vaswani, (c) Melonfire
     

       

    PHP ARTICLES

    - Adding Ordering and Grouping Clauses to the ...
    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 4 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek