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

Meta: April 11th 2008 // PHP // 42,087 views

At this point you will have a working poll system. But what if you want to add your own questions and make new polls? Simple. All you need to do is edit the contents of the database in two places.

8. Firstly open up phpmyadmin. Then click on the database you made and then on the table name poll. Here is where all your polls are stored. Click on the button Insert. Simply make a title for your poll and click go. Next click browse. You will see your entry there, along with an id number. Remember this id number and click on the table name questions.

Do the same with insert, however type in the poll id (pid) which is the number you just remembered, and then the question title. Repeat this process with the question titles and the same pollid until you have all the possible responses you want!

And thats it! You have now set up a new poll. Remember at the start of the tutorial we said we would only show the newest poll, well since your new poll has a greater id number than the previous, it is considered the newest now.

*UPDATE*
The poll bars did not extend to the entire width of the area, that is because we were using strict percentages, in comparison to the total amount of votes. In order to make the bars extend to the full width, and in doing so making the option with the most votes equal 100% we must compare all other votes with that of the most voted option. So to do so open up poll.php and:

After:

1
2
3
4
5
6
if($rows > 0){
		$poll = mysql_fetch_array($query);
		$title = $poll['name'];
	} else {
		$title = 'No Poll Yet';
	}

Add:

1
2
3
4
5
$query = mysql_query("SELECT COUNT(`id`) as hits FROM `responses` GROUP BY `qid`");
	while($row = mysql_fetch_array($query)){
		$me[] = $row['hits'];
	}
	$max = max($me);

Next Find:

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

And replace with:

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

Also another update to fix division by zero:
Find:

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

Replace with:

1
2
3
4
5
if($total > 0 && $responses['total'] > 0){
						$percentage = round(($responses['total'] / $max) * 100);
					} else {
						$percentage = 0;
					}

Done! Now your bars are constructed in comparison to the most popular option!

Tags: , , , , , , , , , , , , , , ,

Pages: 1 2 3 4 5 6 7 8 9

WeDecal.com

Postscript: Leave A Comment // Subscribe (RSS Feed)

3 trackbacks/pingbacks

  1. Pingback: Open Source Blog » Blog Archive » 10 powerful PHP Tutorials for web developer on June 1, 2009
  2. Pingback: Tutorial: How to build a poll system with PHP and mySQL • Jotlab | My Web Development Bookmarks on October 7, 2009
  3. Pingback: fReAkStyLe » Blog Archive » A poll system with PHP and mySQL on November 17, 2009

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

// 65 comments so far.

  1. Cristi // June 11th 2008

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

  2. VoiDeT // June 11th 2008

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

  3. chor khee // July 16th 2008

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

  4. VoiDeT // July 16th 2008

    Hey Chor Khee,

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

  5. Ana // July 25th 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.

  6. Hunter // August 11th 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? :(

  7. Hunter // August 11th 2008

    Nm, fixed it ;)

  8. VoiDeT // August 11th 2008

    And how did you fix it?

  9. Hanayo // September 24th 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….

  10. blckheart // September 25th 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!

  11. VoiDeT // September 27th 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.

  12. BlueDevil18 // September 28th 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?

  13. BlueDevil18 // September 28th 2008

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

  14. Rkrueger // October 12th 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?

  15. Hodde // October 28th 2008

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

  16. Stonedeft // December 13th 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

  17. VoiDeT // December 13th 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

  18. Bjorn // January 13th 2009

    I get the “no poll yet”-message :( Any solutions?

  19. VoiDeT // January 13th 2009

    Did you make sure you entered a poll into the database?

  20. Kim // February 20th 2009

    oh , nice tut, I really took a good hints here ! thanks man and thanks to everybody

  21. victor // March 27th 2009

    hi I have included index.php of this poll onto my homepage but i am getting the following error
    Warning: Division by zero in C:\xampp\htdocs\tutorial\poll.php on line 46

  22. VoiDeT // March 28th 2009

    Victor – Do you have content?

  23. victor // March 30th 2009

    yes i do have content.

  24. VoiDeT // March 30th 2009

    I will review this tutorial’s content on the weekend and add in more tests hopefully.

  25. victor // April 08th 2009

    hi
    i am still looking forward to the solution the problem i am having with the poll as i emailed you on the 27th march 2009….I have included index.php of this poll onto my homepage but i am getting the following error
    Warning: Division by zero in C:\xampp\htdocs\tutorial\poll.php on line 46

  26. VoiDeT // April 08th 2009

    I will look tomorrow for you victor.
    So you have content etc.

  27. VoiDeT // April 08th 2009

    Victor i have looked at the code and indeed yes, it divides by zero,
    I haven’t tested it but it should work now with the test ;)

  28. VoiDeT // April 08th 2009

    By the way i have reuploaded the source

  29. arttech // April 09th 2009

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

    I recieved the same warnings. Fixed it by editing the config.php file. It was just about making sure the “$hostname…etc” sections match with the “$connect = mysql_connect($hostname, $username, $password);
    mysql_select_db($dbname);”
    And, of course, all the db info was correct with no typos.

    I was using dreamweaver to make a db connection. Dreamweaver likes to create its own config file and put it in a separate folder called “Connections” in the root. And it adds info to the config file that Voidet’s didn’t have.

    Great tutorial. Thanks for the work you put into it.

  30. VoiDeT // April 09th 2009

    Arttech!
    Thanks alot for sorting this one one!
    I would never of realised this one, as i dropped dreamweaver for this very reason! It messed with my code and files when i didn’t want it to!

  31. arttech // April 09th 2009

    Sure thing.
    As I am just learning php I’ve run into trouble connecting with the db just because of either incorrect include links or phrasing…

  32. hafiz // April 10th 2009

    hello voidet,

    i stuck in step 2 which is “Lets set up our work space. Make a new folder on your webserver and call it ‘poll’. ”

    Emm…. what did u mean by work space and new folder on your webserver???

    seriously i’m a beginner… i just create a new folder (named poll) under directory : C:\Program Files\xampp\htdocs\
    and paste the config.php inside poll folder

    and whenever i try to navigate the config.php on my browser it shows something like this….

    Warning: mysql_connect() [function.mysql-connect]: Access denied for user ‘hafiz’@'localhost’ (using password: YES) in C:\Program Files\xampp\htdocs\poll\config.php on line 10

    Warning: mysql_select_db() [function.mysql-select-db]: Access denied for user ‘ODBC’@'localhost’ (using password: NO) in C:\Program Files\xampp\htdocs\poll\config.php on line 11

    Warning: mysql_select_db() [function.mysql-select-db]: A link to the server could not be established in C:\Program Files\xampp\htdocs\poll\config.php on line 11

    pls help me!!!

  33. HAFIZ // April 10th 2009

    owh yeah… if i want to try make it as multiple choice poll… what things i have to change in my database????

  34. arttech // April 11th 2009

    Voidet, is it possible for you to show how to use cookies or user id’s instead of ip’s?

  35. VoiDeT // April 11th 2009

    Arttech you can,
    However the point here is that we want to block spam bots!
    What you could do however is have a cool off period for say an hour.
    Select all the IPs in the range from only an hour ago. Not sure if the database will do this but let me know how you go. If you want me to get it done i’d have to ask $10usd to paypal as i don’t have the time at the moment.
    But thanks alot for your replies!

  36. VoiDeT // April 11th 2009

    Hafiz this is a multiple choice poll!
    You needs to add more answers to the poll :)

  37. VoiDeT // April 11th 2009

    Hafiz did you sort your problem out?

  38. alice // April 11th 2009

    (Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in)

    I had the problem too. I just import the sql file again and give the initial value to $me in poll.php. Then will be ok.

    $me[]=0;
    while($row = mysql_fetch_array($query)){
    $me[] = $row['hits'];
    }
    $max = max($me);

    But I would like to know that why $me is an array?

  39. VoiDeT // April 11th 2009

    Because it contains many elements Alice.
    If it were not an array its values would get overridden each time the while looped iterated.

  40. HAFIZ // April 11th 2009

    voidet…

    no… i mean how i can create a poll that allows user to tick more than one… let say the poll has 10 ans and i want to tick 3 ans…. that is what i mean… what i knew is we use the checkbox rather than radio button… right???

    ermmm…. insert text type of data is not my prob… actually i got prob with “post the value of checkbox to database”… how many tables that i must create in database and what type of it… etc.

    and also what are the important element needs to connect PHP with SQL for example the “connect” file…. i’m not sure about it…

    can u teach me voidet???? i really need your help…

    i’m in Malaysia so my online time might be different as yours….

  41. HAFIZ // April 11th 2009

    BTW thank god i found your website…. i’m searching for the best tutorial site so that i can completing my project…. just 3 more days to submit

  42. arttech // April 12th 2009

    Voidet,
    Thanks for the feedback. I’ll look into the time out.

  43. mhemel // April 16th 2009

    Great Tutorial.!!! tnx for sharing one thing i want to find out! i encounter this warning message:

    Warning: Wrong parameter count for max() in C:\xampp\htdocs\poll\poll.php on line 17

    what would be the problem? tnx nwei

  44. VoiDeT // April 16th 2009

    What version of PHP are you using?
    I have not come across this before.

  45. Dan // April 21st 2009

    2mhemel:
    i think the problem is in $me if its not an array (if it’s ==’0′)
    try to replace
    $max = max($me);
    with this:
    if(is_array($me)) { $max = max($me); }
    else { $max=’0′; }

  46. Morris Ericsson // April 29th 2009

    Hi! I really appreciate your turtorials, but also got the message No Poll Yet -and yes – I entered a poll into the database. Any solutions??

  47. Morris Ericsson // April 30th 2009

    Hi again. I have fixed my problem by using config.php instead of my own start.php. Maybe I had too much script in that page??? Now I have “insert config.php in my start.php. However, I get no value on my vote … but have not tried to solve that problem yet.

  48. Dee // June 06th 2009

    I keep getting this error…Warning: mysql_connect() [function.mysql-connect]: Can’t connect to local MySQL server through socket ‘/usr/local/mysql-5.0/data/mysql.sock’ (2) in /home/content/j/u/i/juicer40/html/apoll/config.php on line 8

  49. Artech // July 16th 2009

    Voidet. Hello again.
    Polls are still working great. You can see them on this site http://www.leerepublicanwomen.com

    Today I changed the questions and noticed that there is a limit on the number of characters in the poll.

    Is that limit built into your tutorial somewhere that I haven’t found, or is in in the php admin on my hosting service?

    Thanks again for your hard work.

  50. VoiDeT // July 30th 2009

    That’s great news!
    However:
    “Use this script if you like, but don’t remove the copyright tag.”

    I would appreciate some support in return :) Paypal donations always accepted :) voidet :at: nightgen :dot: com

  51. Artech // July 31st 2009

    voidet. Of course! Sent you some cash and put a link in.
    Many thanks for your hard work!

  52. VoiDeT // July 31st 2009

    Hey!
    Thanks alot for the donation!
    I really appreciate that! If people are using the tutorial as a learning tool i’m all for it, we both can build something up that way. But if people are going to use it for their own web apps, it’s not right to just take and not give anything back :)
    But thanks alot for the donation! I am glad it worked out for you :D Also if you need any future help with anything just let me know!

  53. Artech // July 31st 2009

    Honestly it was a learning tool for me. And I ended up using it successfully which I thought was very cool.
    I am happy to give back and may call on you again. Thanks very much.

  54. VoiDeT // July 31st 2009

    Hey Artech!

    Really cool portfolio you have!
    Love the graphics!

  55. Artech // July 31st 2009

    Thanks Voidet.
    I enjoy working with flash. Creating with graphics in mind is usually how I approach things. But I’m getting more and more into the scripting side of things. Really appreciating the functionality and management.

  56. VoiDeT // July 31st 2009

    You should get into the frameworks!
    Just jump into CakePHP :D

  57. frank // August 24th 2009

    will this code work if i want to ask a series of independant yes or no question that i want to rate separately?

  58. VoiDeT // August 24th 2009

    This is a poll script.
    To turn it into a survey type program would require some refactoring.
    Not too much if you want it hardcoded, but alot if you want it to be dynamic :)

  59. Zilus // August 25th 2009

    Hi, great tutorial, thanks man. :D

  60. iz // August 27th 2009

    hi, anyone know how we get the value of $responses['total'] hmm i starter in php wondering where we get the ‘total’ from? thx for any help..

  61. VoiDeT // August 27th 2009

    IZ please clarify here!
    Do an echo $responses['total'] to output the total number of responses!

  62. Diogo // October 14th 2009

    Really good tutorial!! THX!! I’m just modifying a bit to fit on my page and to my taste.

    But again, thx, i learned a lot here!

  63. Ralph // January 11th 2010

    Hi.. nice tutoria! i have a question

    Warning: Wrong parameter count for max() in C:\wamp\www\poll\poll.php on line 17

    what does it mean? and how can i solve it? thanks…

  64. VoiDeT // January 15th 2010

    Hey Ralph,

    Below “$query = mysql_query(“SELECT COUNT(`id`) as hits FROM `responses` GROUP BY `qid`”);”
    Add:

    $me = array();

  65. Ralph // January 21st 2010

    thanks VoiDeT.. ill try it! ^__^

Who Are You?

Your Email Address

Your Website

:D :) :o :eek: :( :lol: :wink: :arrow: :idea: :?: :!: :evil: :p

You can follow any responses to this entry via its RSS comments feed. You may also leave a trackback by clicking this link.