Tutorial: How to build a poll system with PHP and mySQL

Pages: 1 2 3 4 5 6 7 8 9

First up we have:

  1. $total = mysql_query("SELECT `questions`.`pid` FROM  `responses`, `questions` WHERE `responses`.`qid`=`questions`.`id` AND pid='".$poll['id']."'");
  2.   $total = mysql_num_rows($total);

This selects all the responses from the selected poll. It then puts it in a variable which we can use to calculate the number of rows from. This calculation is important as it allows us to firstly show the total number of vote, and secondly allows us to calculate the bar lengths used to graphically depict the results.

The next part is HTML, you don't need to worry about this too much, just opening up a table and showing the title of the poll.

  1. <table width="300" cellpadding="0" cellspacing="0" border="0" align="center">
  2.   <tr>
  3.     <td valign="top" align="center"><?php echo $title; ?></td>
  4.   </tr>

We come to our next PHP section

  1. <?php
  2.     $query = mysql_query("SELECT * FROM `questions` WHERE `pid`='".$poll['id']."' ORDER BY `question`");
  3.     $questions = mysql_num_rows($query);
  4.     if($questions > 0){
  5.   ?>

This selects all of the question information from the database, so that we can get the question titles etc and display it. Nothing too complex here. Just see if there are questions to show, if there are proceed.

  1. <tr>
  2.     <td valign="top">
  3.     <table width="100%" cellpadding="0" cellspacing="0" border="0">

After a little bit more HTML we come to our next PHP section:

  1. <?php
  2.         while($question = mysql_fetch_array($query)){
  3.           $responses = mysql_query("SELECT count(id) as total FROM `responses` WHERE qid='".$question['id']."'");
  4.           $responses = mysql_fetch_array($responses);
  5.           $percentage = round(($responses['total'] / $total) * 100);
  6.           $percentage2 = 100 - $percentage;
  7.       ?>

This is executed obviously as our php cycles through each question. We have used a SQL statement to calculate how many responses were made in each question. That then gets fed into a mysql_fetch_array command so we can get that value. From there we put it into an equation.

  1. $percentage = round(($responses['total'] / $total) * 100);

Get the number of responses, divide it by the total number of responses, multiply it by 100 and round it off to an integer value. Simple! So if there are two votes on your poll, on two different questions, the percentage will obviously equal 50%. We calculate the remainder value with $percentage2. We then use these values to graphically display our results:

  1. <table width="100%" cellpadding="0" cellspacing="0" border="0">
  2.             <tr>
  3.               <td valign="top" width="<?php echo $percentage; ?>%" <?php if($percentage > 0){?>style="background: url('images/bar.jpg') repeat-x;"<?php } ?>><img src="images/dot.gif" width="1" height="19" /></td>
  4.               <td valign="top" width="<?php echo $percentage2; ?>%"></td>
  5.             </tr>
  6.           </table>

This gets each percentage and sets the width of the table cells, the left one containing an image which repeats it self over the width of the table cell, aka a background! This line here:

  1. <?php if($percentage > 0){?>style="background: url('images/bar.jpg') repeat-x;"<?php } ?>

Checks if the percentage equals 0. If it does, don't worry about displaying a background image. All you will see then is just a 1pixel image, which is not theoretically correct.

  1. <td valign="top"><?php echo $responses['total']; ?></td>

We then show the number of votes for that question and then leave the questions cycle. Lastly we display the total number of votes (remember how we calculated $total above) with:

  1. <tr>
  2.         <td valign="top" colspan="3" align="center">Total Votes: <?php echo $total; ?></td>
  3.       </tr>

Then we close all if statements and finish the page. Next i will teach you how to add questions and make new polls via the direct editing of the database.

Pages: 1 2 3 4 5 6 7 8 9

Tags
, , , , , , , , , , , , , , ,

  1. 17 Responses to “Tutorial: How to build a poll system with PHP and mySQL”

  2. By Cristi ROMANIA Windows XP Mozilla Firefox 2.0.0.14 on Jun 11, 2008

    It would be perfect if it had a form to add the question and a form to edit them. Anyway Good Job.

  3. By VoiDeT AUSTRALIA Mac OS X Safari 525.20 on Jun 11, 2008

    Yep sure.
    You should take the guestbook tutorial and build that feature yourself! It is not hard at all

  4. By chor khee SINGAPORE Windows XP Internet Explorer 7.0 on Jul 16, 2008

    nice one man! just a simple question. Can this be done using jsp and mYsql? are there any links for that?

  5. By VoiDeT AUSTRALIA Mac OS X Safari 525.20.1 on Jul 16, 2008

    Hey Chor Khee,

    I don’t know JSP, sorry.
    Have fun with the port!

  6. By Ana Windows XP Internet Explorer 7.0 on Jul 25, 2008

    Thank you very much it really is great, it gave me the whole picture. I am using Access data base, how can I use this nice piece of code for Access. Thanks again.

  7. By Hunter UNITED STATES Windows Vista Mozilla Firefox 3.0.1 on Aug 11, 2008

    Hi,

    I downloaded the source, and uploaded it in tact, minus editing in my database information.

    I get this error:

    http://www.nineprinces.org/hunter/php/tutorials/


    Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/backline/public_html/hunter/php/tutorials/poll.php on line 4″

    What’s up w/ that? :(

  8. By Hunter UNITED STATES Windows Vista Mozilla Firefox 3.0.1 on Aug 11, 2008

    Nm, fixed it ;)

  9. By VoiDeT AUSTRALIA Mac OS X Safari 525.20.1 on Aug 11, 2008

    And how did you fix it?

  10. By Hanayo UNITED STATES Mac OS X Mozilla Firefox 3.0.1 on Sep 24, 2008

    I tried working on it but I as totally lost when it came to the whole phpmyAdmin thing??

    I couldn’t figure out what you were talking about the click Insert or whatever since I didn’t see that anywhere on my page…

    Like I know how to read html/css fairly well and can read xhtml. But php is what I’m learning, and so i know i put the codes in all the right spots but I don’t know what you meant by that and I tried but I dont’ think i got it…

    http://www.aestheticloveinc.com/poll/index.php and it’s just blank….

  11. By blckheart Windows XP Mozilla Firefox 2.0.0.17 on Sep 25, 2008

    RE: And how did you fix it? Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in

    To fix the error, you will have to connect to the database. In the downloaded files there is no config.php file or db.inc file to connect to the database, therefore the mysql_num_rows cannot find any info from the database, because there is no connection to the database. Or at least this is what happened in my case.

    To connect to the database use the following code in the poll.php file or create a seperate config.php file and just use an include ‘config.php’; or require ‘config.php’; in the top of your poll.php file

    //Connection to Database
    $hostName = “localhost”;
    $databaseName = “yourdatabasename”;
    $databaseusername = “yourdbusername”;
    $dbpassword = “yourdbpassword”;

    $connect = @mysql_connect($host, $yourdbusername, $yourdbpassword);
    if (!mysql_select_db($databaseName, $connect))
    echo ‘Could not connect to database’;

    I hope this helps, i dont know why someone would ask for help on the error and then say he fixed it without giving a solution, he has the time to ask but not the time to help, i think that sucks!

  12. By VoiDeT AUSTRALIA Mac OS X Safari 525.20.1 on Sep 27, 2008

    blckheart what do you think is sitting in the root folder? would it be a config.php file by anychance? With this code in it?

    < ?php

    //database settings

    $hostname = 'localhost';
    $username = 'yourusername';
    $password = 'yourpassword';
    $dbname = 'poll';

    $connect = mysql_connect($hostname, $username, $password);
    mysql_select_db($dbname);

    ?>

    Look at the files.

  13. By BlueDevil18 UNITED STATES Windows XP Internet Explorer 7.0 on Sep 28, 2008

    I set everyhing up. Added a New Poll and Questions to the poll with the correct pid. However, when I browse to the file(poll.php) on the server, it still comes up “No Poll Yet” Am I not doing something?

  14. By BlueDevil18 UNITED STATES Windows XP Internet Explorer 7.0 on Sep 28, 2008

    I need some help with this. I think i set up up correctly, but i still get “no poll yet”

  15. By Rkrueger UNITED STATES Windows XP Google Chrome 0.2.149.30 on Oct 12, 2008

    hey i was doing this and it came up with the error that the function “max()” doesn’t have enough parameters..
    can someone check this out?

  16. By Hodde DENMARK Windows XP Mozilla Firefox 3.0.3 on Oct 28, 2008

    I get the “no poll yet”-message too.. and i’m also pretty sure i set the poll up correctly..

  17. By Stonedeft PHILIPPINES Windows XP Safari 525.17 on Dec 13, 2008

    You should have separated codes and html. It gets real confusing I have to strip html tags the poll.php for me to review the code.

    Well I got the idea but man you should recode this to for web 2.0 standards

  18. By VoiDeT CANADA Mac OS X Safari 525.27.1 on Dec 13, 2008

    Thank you for the comment,
    Web 2.0 standards in php LOL :D Maybe you could say something like, maybe you should use objects, or logic from design separation, but web 2.0 standards haha

Post a Comment