Poll?

Part 5, Getting the results back.

whilst this is meant to be telling you how to create a graphical poll, firstly, lets get the results back in a text format.

as always, include the connection file to setup the database connection.

Code:
<?php
include('connect.php');
then get the id of the poll that is of interest,
Code:
$pollid = $_GET['pid'];

now select everything regarding that poll from the database,
Code:
$query = "select * from polls where poll_id = '$pollid' order by option_id asc";
$result = mysql_query($query) or die('Query failed: ' . mysql_error() . '<hr>There has been an error in the application, please contact the administrator</b>');

and get everyhing fromthe database pushed into arrays for the results.

Code:
$x=1;
while ($line = mysql_fetch_array($result, MYSQL_ASSOC))
{
//store results in temporary arrays
	$poll_tittle[$x] = $line['poll_tittle'];
	$option_title[$x] = $line['option_tittle'];
	$count[$x] = $line['count'];
	$x++;
}

and start a table, in the exact same way that the voting page was made.

Code:
//set up table for printing results
print "<table>
		<tr>
			<td colspan=2>";
//print poll title as header
			echo $poll_title[1];
print "	 </td>
		</tr>";


now print all the reulsts into that table...

Code:
for ($y=2;$y<$x;$y++)
{
	print "
		<tr>
			<td>";
				echo $option_title[$y];
	print " </td>
			<td>";
				echo $count[$y];
	print" </td>
		</tr>";
}
then just finish up the page...

Code:
print "</table>";
 
 
?>

You need to make sure that yo understand what is selected from the database before you move onto the next part of the tutorial which will cover creating bar charts.
 
complete code
Code:
<?php 
include('connect.php');
//manually set pollid, in practise this will be obtained from a form variable.
//$pollid = 1;
$pollid = $_GET['pid'];
//select results of relevant poll
$query = "select * from polls where poll_id = '$pollid' order by option_id asc";
$result = mysql_query($query) or die('Query failed: ' . mysql_error() . '<hr>There has been an error in the application, please contact the administrator</b>');
$x=1;
while ($line = mysql_fetch_array($result, MYSQL_ASSOC))
{
//store results in temporary arrays
	$poll_tittle[$x] = $line['poll_tittle'];
	$option_title[$x] = $line['option_tittle'];
	$count[$x] = $line['count'];
	$x++;
}
//set up table for printing results
print "<table>
		<tr>
			<td colspan=2>";
//print poll title as header
			echo $poll_title[1];
print "	 </td>
		</tr>";
//print poll results in a loop for however many poll options there are.
for ($y=2;$y<$x;$y++)
{
	print "
		<tr>
			<td>";
				echo $option_title[$y];
	print " </td>
			<td>";
				echo $count[$y];
	print" </td>
		</tr>";
}
print "</table>";
 
?>
 
Part 6, drawing pictures.

I decided that I'd split up the creation of the bar charts into two parts, the first wil cover how to draw simple pictures with boxes in PHP, then I'll do the part of actually diplaying the results a bit later,
that way the maths part of displaying results...


right to draw pictures we'll be using the GD tools on php...

I'll start with drawing a small white box on a black background


making a canvas,
all images in PHP, (and in C if you use GD in C) have image pointers,
in this tutorial the image pointer in $im

Code:
$im = ImageCreate (100, 300);
the height is the first number, the width is the second.

next you need to allocate colours to be used in the image, the first colour allocated will be the background colour of the canvas.

Code:
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);

now we have a black canvas...

we'll draw a white box on it... starting 5 pixels from the left and 6 pixels from the top, ending 295 pixel from the left and 94 pixels from the top
Code:
ImagefilledRectangle($im, 5, 6, 295, 94, $white);


now we'll save the image, (this is useful if you want to displa the results a lot without having your server re-draw them all the time.

Code:
	imagejpeg ($im,"test.jpg","-1");
now we clear the memory space that the pointer occupied.
Code:
	imagedestroy($im);

now print some html to show that image
Code:
 print "<img src=\"test.jpg\">";


so all in all we have

Code:
<?php

$im = ImageCreate (100, 300);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);
ImagefilledRectangle($im, 5, 6, 295, 94, $white);
imagejpeg ($im,"test.jpg","-1");
imagedestroy($im);
print "<img src=\"test.jpg\">";
?>

and that should display a black canvas with a white box in the middle.

see, it's quite easy to draw pictures in php
 
part 7, displaying results as a bar chart...

I'm not going to go through the idea of getting results from the database and loading them into an array since that already been cpovered...

we'll start from this code...

Code:
<?php
include('connect.php');
 
$pollid = $_GET['pid'];
 
//select results of relevant poll
$query = "select * from polls where poll_id = '$pollid' order by option_id asc";
$result = mysql_query($query) or die('Query failed: ' . mysql_error() . '<hr>There has been an error in the application, please contact the administrator</b>');
 
$x=1;
while ($line = mysql_fetch_array($result, MYSQL_ASSOC))
{
//store results in temporary arrays
	$poll_title[$x] = $line['poll_title'];
	$option_title[$x] = $line['option_title'];
	$count[$x] = $line['count'];
	$x++;
}

now we need to get a canvas size...

I choose (arbitrarily) that the bars will be drawn horizontally, and the canvas will be 400px wide, and a variable height to account for an unknown amount of pol options.

Code:
$canvasx = 400;
$canvasy = $x*18+10;
[code]
I multiply by 18 to allow for the height of te bars, and some white space, the +10 is so there will be some white space at the bottom of the cavas as well...
 
 
now we draw the canvas and allocate some colours.
[code]$im = ImageCreate ($canvasx+10, $canvasy);
 
//set up colours to be used, these could be pulled from a database or style sheet
$white = imagecolorallocate($im, 255, 255, 255);
$fontcolour = imagecolorallocate($im, 0, 0, 0);
$fillcolour = imagecolorallocate($im, 255, 128, 64); //orange

now before we draw the title of the poll on the chatrt we need to find out how long the title is so that we can centre it, to do this we use strlen, and multiply by the approximate width of the charectors.

then divide by two to get the offset from the centre
Code:
$px = (imagesx($im) - 7.5 * strlen($poll_title[1])) / 2;
the position of the text is stored as a number in the variable $px

now we draw the poll title onto the canvas
Code:
	imagestring($im, 5, $px, 0, $poll_title[1], $fontcolour);

now, because the canvas size is fixed at 400 we need to make sure everything else will fit into that space, the length of the bars must not exceed 400px, since then they'd go off the canvas, but they must also be in aspect to each other...

so lets find the largest option count in the database, we also find the larget option text, because we'll be writting the options on the picture as well...

Code:
$option_len = 1;
$largest_poll = 1;
//scroll through option titles to find the longest.
for ($y=2;$y<$x;$y++)
{
	if ($option_len<strlen($option_title[$y]))
	{
		$option_len = strlen($option_title[$y]);
	}
		if ($largest_poll<$count[$y])
	{
		$largest_poll = $count[$y];
	}
}

now we calculate the position to start drawing bars, this is at a point after the text since we don't want to write text options over the top of the bars, or visa versa.

Code:
$startx = ((8.5 * $option_len)+15);

now figure out how much space is left to draw the bars..
Code:
$available_space = $canvasx - $startx;

now work out a scale factor for how big the bars can be based on the amount of space left and the largest count which mussn't go off the edge of the canvas...
Code:
$scalor = $available_space * $largest_poll;
$scalor = $available_space / $scalor;
The maths here isn't so important, if you understand whats going on then great, if you need a better explenation of whats going on then just ask.

now we draw the poll option text onto the chart, and we add the bars, that are all scaled....

Code:
for ($y=2;$y<$x;$y++)
{
	//calculate the position down the canvas for the option titles
	$down_position = $y*18;
	//drawthe option titles on the canvas
	imagestring($im, 5, 5, $down_position, $option_title[$y], $fontcolour);
 
	//calculate co-ordiantes to draw bars
	//find the length of the bar needed
	$bar_length = ($available_space * ($scalor * $count[$y]));
	//find the co-ordinate ofthe end of the bar based on the start value (i.e where the text stops)
	$endx = $startx + $bar_length;
	$starty = $down_position+5;
	$endy = $starty +4;
	//draw filled box
	ImagefilledRectangle($im, $startx, $starty, $endx, $endy, $fillcolour);
	//draw outline around the box
	ImageRectangle($im, $startx, $starty, $endx, $endy, $fontcolour);
}
You might have noticed that I introduced imagerectangle function as well as the imagefilledrectangle, this was so the bars on the chart have an outline.


now we just save the picture and clear up the memory space.

Code:
	/*save picture to minimise future processing*/
	imagejpeg ($im,"$pollid.jpg","-1");
 
	/*clean up memory space*/
	imagedestroy($im);
 
print "<img src=\"$pollid.jpg\">";
?>
Notice that the picture is saved as the poll id, this may mean that your server fills up with poll images, so you might like to change this so that the polls are worked out each time,

the point is it was written for my server where space comes second to speed.


anyway, the full code for this pagethat draws charts is
Code:
<?php
include('connect.php');
 
$pollid = $_GET['pid'];
 
//select results of relevant poll
$query = "select * from polls where poll_id = '$pollid' order by option_id asc";
$result = mysql_query($query) or die('Query failed: ' . mysql_error() . '<hr>There has been an error in the application, please contact the administrator</b>');
 
$x=1;
while ($line = mysql_fetch_array($result, MYSQL_ASSOC))
{
//store results in temporary arrays
$poll_title[$x] = $line['poll_title'];
$option_title[$x] = $line['option_title'];
$count[$x] = $line['count'];
$x++;
}
 
//set the size of the canvas, one standard, the other depends on the amount of poll options
$canvasx = 400;
$canvasy = $x*18+10;
 
//create canvas
$im = ImageCreate ($canvasx+10, $canvasy);
 
//set up colours to be used, these could be pulled from a database or style sheet
$white = imagecolorallocate($im, 255, 255, 255);
$fontcolour = imagecolorallocate($im, 0, 0, 0);
$fillcolour = imagecolorallocate($im, 255, 128, 64); //orange
 
//see length of poll title and canvas size to centre the title in the canvas
$px = (imagesx($im) - 7.5 * strlen($poll_title[1])) / 2;
 
/*draw title*/
imagestring($im, 5, $px, 0, $poll_title[1], $fontcolour);
 
$option_len = 1;
$largest_poll = 1;
//scroll through option titles to find the longest.
for ($y=2;$y<$x;$y++)
{
if ($option_len<strlen($option_title[$y]))
{
$option_len = strlen($option_title[$y]);
}
if ($largest_poll<$count[$y])
{
$largest_poll = $count[$y];
}
}
//calculate co-ordinate to start drawning bars.
$startx = ((8.5 * $option_len)+15);
 
//get the available space in which to draw bars
$available_space = $canvasx - $startx;
 
//wrk out a scale factor for resizing lesser counts, so that the poll with the highest count reacheste end of the chart
$scalor = $available_space * $largest_poll;
$scalor = $available_space / $scalor;
 
//print poll results in a loop for however many poll options there are.
for ($y=2;$y<$x;$y++)
{
//calculate the position down the canvas for the option titles
$down_position = $y*18;
//drawthe option titles on the canvas
imagestring($im, 5, 5, $down_position, $option_title[$y], $fontcolour);
 
//calculate co-ordiantes to draw bars
//find the length of the bar needed
$bar_length = ($available_space * ($scalor * $count[$y]));
//find the co-ordinate ofthe end of the bar based on the start value (i.e where the text stops)
$endx = $startx + $bar_length;
$starty = $down_position+5;
$endy = $starty +4;
//draw filled box
ImagefilledRectangle($im, $startx, $starty, $endx, $endy, $fillcolour);
//draw outline around the box
ImageRectangle($im, $startx, $starty, $endx, $endy, $fontcolour);
}
 
	/*save picture to minimise future processing*/
	imagejpeg ($im,"$pollid.jpg","-1");
 
	/*clean up memory space*/
	imagedestroy($im);
 
print "<img src=\"$pollid.jpg\">";
?>


I realise that last part kind of flew by... so if yu have any troubles understanding it... then just ask...
 
After all of that you should now have 5 files.

an HTML file called create poll.html (part 1)

a php file called connect.php (part 3)

a file called post.php (part 4)

a file called text_poll_result.php (part 5)

and a file called bar_poll_result.php (part 7)


perhaps a file called test.php if you did the bit in part 6
 
ROOT!!1 YOU.... ARE............... AWESOME!!!!! Mega reputation for you!

I gotta try this out now.


EDIT> Ah stupid forum won't let me give you reputation. I have to spread some around first. Don't worry though. Reputation is on the way!
 
the actual poll part with the voting and everything works fine in firefox, it's just the bit about creating polls with the amount of options needed...

I suppose that you could re-write the little jscript function to work with proper javascript, but I'm not sure how you've get it to keep the exiasting options you've already put in.
 
Back
Top Bottom