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

Meta: April 11th 2008 // PHP

6. What we need now is a way to test if there are questions or not in the poll. So now that we know we have a poll, we can begin showing its questions. So lets add some php code into our HTML. I prefer nesting PHP in html, as HTML nested in php can sometimes look very ugly. Both are ugly, but what can you do? So add the code below this line:

This:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<table width="300" cellpadding="0" cellspacing="0" border="0" align="center">
	<tr>
		<td valign="top" align="center"><?php echo $title; ?></td>
	</tr>
	<?php
		$query = mysql_query("SELECT * FROM `questions` WHERE `pid`='".$poll['id']."' ORDER BY `question`");
		$questions = mysql_num_rows($query);
		if($questions > 0){
	?>
	<tr>
		<td valign="top">
		<form name="poll" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
		<table width="100%" cellpadding="0" cellspacing="0" border="0">
			<?php
				while($question = mysql_fetch_array($query)){
			?>
				<tr>
					<td valign="top"><input type="radio" name="questions" value="<?php echo $question['id']; ?>" /></td>
					<td valign="top" width="100%"><?php echo $question['question']; ?></td>
				</tr>
			<?php
			}
			?>
			<tr>
				<td valign="top" colspan="2" align="center"><input type="submit" name="vote" value="Submit Vote" /></td>
			</tr>
		</table>
		</form>
		</td>
	</tr>
	<?php
		}
	?>
</table>

Below this:

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

Yep, big nesting of HTML and PHP. Time to explain it!

Firstly we make another query to the database. The purpose of this one is to find the questions of the poll. So it asks: Give me everything that has the id of the poll we are looking for. Remember how we selected the poll title above and got the name with $poll['name']? Well we are now using the $poll['id'] column. So what is happening is we are using the id of the poll, and matching it up to any matching records in the questions table. Thats right! A series of questions belong to a single poll, one to many relationship, A+.

1
2
$questions = mysql_num_rows($query);
		if($questions > 0){

We then get the number of rows and then test if the poll has any questions or not. If it doesnt then we skip the entire questions cycle and just close off the html. We then set up the HTML to display a form etc. This is not a html class. But next comes the questions cycle, where we use the response from the database.

1
while($question = mysql_fetch_array($query)){

This is a common way to run through an array. It executes row by row, until there are no more rows to display. All items from the array are accessible via the $question variable, much like we did above with the $poll variable. So through each look the code will display:

1
<input type="radio" name="questions" value="<?php echo $question['id']; ?>" />

This prints out a radio button, with the $question id as each ones value, this is so we can later track what item was selected, and the question title itself.

1
<input type="submit" name="vote" value="Submit Vote" />

A submit button is then displayed. If we didn’t have our database setup the way it is, we might have to use a hidden field here, to display the poll id number in the form somewhere, but we will just be inserting the question id’s into the database, as they are unique and an easy way to track! The loop and the number of rows test is then closed off and that is that for the interface for user input!

If this section has confused you, try to look at the PHP itself, ignore the HTML code. When programming always have the logic clear in your head, styling and design comes later. So if you don’t follow how the selection is being tracked yet, don’t worry, you will probably realise how in this next section.

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

Pages: 1 2 3 4 5 6 7 8 9

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

1 trackbacks/pingbacks

  1. Pingback: Open Source Blog » Blog Archive » 10 powerful PHP Tutorials for web developer on June 1, 2009

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

// 48 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

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.