The last analysis, I promise! The font used doesn’t matter, but using a big font (4, 5) might hurt the look and even the readability of your graph. The x coordinate here is the same as the x coordinate in the previous imagestring. The y coordinate uses the same calculation that was used to determine the height of the bar (200-$per) with 15 subtracted from it so the text isn’t drawn inside the bar. “$rper%” is the variable
$rper
with the percent symbol added to it (otherwise, its just a number). Well, that’s all the code. Here’s the final script:
<?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);
imagestring ($im, 1, ($xval+($barwidth/2)), 205, $voteoption, $black);
imagestring ($im, 2, ($xval+($barwidth/2)), ((200-$per)-15), "$rper%", $bla);
$xval+=($barwidth+10)
}
imagepng($im);
?>
Conclusion
Dynamic graphs are a great way to combine the power of PHP with MySQL and GDLib. It offers data in an easily readable format to your viewers. This article barley scratches the surface of what is possible with dynamic graphing, let alone GDLib. One could make bars of alternating colors, or even color-code them from highest to lowest. Different types of graphs can be made just as easily: line graphs, pie graphs etc. With a little creativity, you can even pull off a pseudo-3d effect using imageline. The possibilities are endless, and the only way to ensure that you are getting the most out of GDLib is to read through all the functions in the PHP manual. I hope you enjoyed and benefited from this article as much as I would have had some one wrote it before me :). Good luck, and happy graphing.
-Ramsey Nasser