PHPBuilder - Dynamic Graphs with PHP, MySQL and GD Page 8



RSS Twitter
Articles Php Functions

Dynamic Graphs with PHP, MySQL and GD - Page 8

by: Ramsey Nasser
|
February 19, 2003

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 ($im25500);
$black imagecolorallocate ($im000);
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 
($im1, ($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 
($im2, ($xval+($barwidth/2)), ((200-$per)-15), "$rper%"$black);
?>

« Previous Page
1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
|
9
Next Page »

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
Ramsey Nasser

Comment:



Comment:

(Maximum characters: 1200). You have characters left.