Let’s take a look at our code so far, as its enough to draw a full graph:
<?php
header ("Content-type: image/png");
$im = imagecreatefrompng ("graphtemp.png");
$red = imagecolorallocate ($im, 255, 0, 0);
$black = imagecolorallocate ($im, 0, 0, 0);
mysql_connect("localhost", "user", "password");
mysql_query("USE database");
$optionsquery = mysql_query("SELECT * FROM voteoptions");
$numoptions = mysql_num_rows($optionsquery);
$pollquery = mysql_query("SELECT * FROM poll");
$numvotes = mysql_num_rows($pollquery);
$xval = 30;
$barwidth = floor(300/$numoptions);
for ($i=0;$i<=($numoptions-1);$i++)
{
$voteoption = mysql_result($optionsquery,$i,'name');
$votevalue = mysql_result($optionsquery,$i,'value');
$currentnumquery = mysql_query("SELECT * FROM poll WHERE vote='$votevalue'");
$currentnum = mysql_num_rows($currentnumquery);
$per = floor(($currentnum/$numvotes)*184);
$rper = floor(($currentnum/$numvotes)*100);
imagefilledrectangle ($im, $xval, (200-$per), ($xval+$barwidth), 200, $red);
imagerectangle ($im, $xval, (200-$per), ($xval+$barwidth), 200, $black);
$xval+=($barwidth+10)
}
imagepng($im);
?>
Note the addition of the closing brackets and the incrementing of $xval (as I promised). If all went well, you should get a nice red graph. Well, actually, a nice series of red bars. There is no indication as to which bar means what, and how much each bar is. Although nice, this graph is essentially useless. Not to worry, this can be fixed. A few imagestrings will solve all your problems. The most important thing is to label the bars. Take a look at this bit of code:
<?php
imagestring ($im, 1, ($xval+($barwidth/2)), 205, $voteoption, $black);
?>
I used font one, its small and practical, but it really doesn’t matter. The x coordinate is the current $xval plus half the
$barwidth
. This is an attempt to center the text, and it works pretty well (it’s not that good actually, there are many better ways to center text, but for simplicity, I’m not going to include it). The y coordinate, 205, puts it a little lower than the bottom line. The variable $voteoption
is used as the text to be written, and the color $black
is used as the, well, color. This line goes right after the imagerectangle
, and before the $xval
increment. To finish it all off, we’ll add text on to of the bar saying what percent of the voters chose this option. The code is as follows:
<?php
imagestring ($im, 2, ($xval+($barwidth/2)), ((200-$per)-15), "$rper%", $black);
?>