Syed Abdul Baqi

Dynamic Graph-Code using GD Library in PHP

Posted on: June 24, 2009

Hello Everybody,

Recently I have coded one dynamic graph-code for PHP using GD Library. Just want to share the code with all of you guys. Feel free to make any modifications and use it in your projects. You can find the code below:

graphcode.php

<?php

$data1 = $_GET['tot'];
$data2 = $_GET['correct'];

$im = imagecreate(100,20); // width , height px

$lightblue = imagecolorallocate($im,226,224,224); 

if($data2 > 0 && $data2 <= 10)
{
 $darkblue = imagecolorallocate($im,255,0,1);
}
elseif($data2 > 10 && $data2 <= 20)
{
 $darkblue = imagecolorallocate($im,243,80,1);
}
elseif($data2 > 20 && $data2 <= 30)
{
 $darkblue = imagecolorallocate($im,244,116,1);
}
elseif($data2 > 30 && $data2 <= 40)
{
 $darkblue = imagecolorallocate($im,243,147,1);
}
elseif($data2 > 40 && $data2 <= 50)
{
 $darkblue = imagecolorallocate($im,243,189,1);
}
elseif($data2 > 50 && $data2 <= 60)
{
 $darkblue = imagecolorallocate($im,243,225,1);
}
elseif($data2 > 60 && $data2 <= 70)
{
 $darkblue = imagecolorallocate($im,214,243,1);
}
elseif($data2 > 70 && $data2 <= 80)
{
 $darkblue = imagecolorallocate($im,189,243,1);
}
elseif($data2 > 80 && $data2 <= 90)
{
 $darkblue = imagecolorallocate($im,140,243,1);
}
elseif($data2 > 90)
{
 $darkblue = imagecolorallocate($im,92,243,1);
}

$x = 0;         // bar x1 position
$y = 20;         // bar $y1 position
$x_width = 0;     // width of bars
$y_ht = 20;     // height of bars, will be calculated later

for ($i=1;$i<$data1;$i++)
{
 $x_width = $i * 1;
 imagerectangle($im,$x,$y,$x+$x_width,($y-$y_ht),$lightblue);
}

$y = 20;
$y_ht = 20;

for ($i=1;$i<$data2;$i++)
{
 $x_width = $i * 1;
 imagerectangle($im,$x,$y,$x+$x_width,($y-$y_ht),$darkblue);
}

imagejpeg($im);

?>

You can use the above file as shown below:

<img src=graphcode.php?tot=100&correct=75 />

You will have to pass 2 query string variables to file as shown above. The first variable (tot) represents total percentage, and second variable (correct) represents correct percentage. Also make sure you have GD library enabled in PHP.ini

Let me know, how I can make the script more flexible.

Comments are welcomed…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: