SQL concepts used: SELECT ยท ORDER BY
Draw the grid first, then draw the data line so the series remains visually prominent.
<?php
$image = imagecreatetruecolor(600, 360);
$background = imagecolorallocate($image, 255, 255, 255);
$grid = imagecolorallocate($image, 220, 220, 220);
imagefilledrectangle($image, 0, 0, 599, 359, $background);
for ($x = 50; $x <= 550; $x += 50) {
imageline($image, $x, 30, $x, 320, $grid);
}
for ($y = 70; $y <= 320; $y += 50) {
imageline($image, 50, $y, 550, $y, $grid);
}
?>imageline ($im,$x2, $y_max,$x2,$y2,$grid_color);
Of course we have to set the value of $grid_color before this line. We will get image like this. For a better clarity than previous tutorial on basic of line graph we have reduced the height of the graph.
<?php
require "config.php"; // provides $pdo
$stmt=$pdo->query('SELECT month, sales FROM gd_graph ORDER BY id');
$points=$stmt->fetchAll(PDO::FETCH_ASSOC);
$x_gap=40; // The gap between each point in y axis
$x_max=$x_gap*13; // Maximum width of the graph or horizontal axis
$y_max=160; // Maximum hight of the graph or vertical axis
// Above two variables will be used to create a canvas of the image//
$im = imagecreatetruecolor($x_max, $y_max);
$background_color = ImageColorAllocate ($im, 234, 234, 234);
$text_color = ImageColorAllocate ($im, 233, 14, 91);
$graph_color = ImageColorAllocate ($im,25,25,25);
$grid_color = ImageColorAllocate ($im,125,125,125);
$x1=0;
$y1=0;
$first_one="yes";
foreach($points as $nt){
//echo "$nt[month], $nt[sales]";
$x2=$x1+$x_gap; // Shifting in X axis
$y2=$y_max-$nt['sales']; // Coordinate of Y axis
ImageString($im,2,$x2,$y2,$nt['month'],$graph_color);
// Drawing the grid vertically//
imageline ($im,$x2, $y_max,$x2,$y2,$grid_color);
//Line above is to print month names on the graph
if($first_one=="no"){ // this is to prevent from starting $x1= and $y1=0
imageline ($im,$x1, $y1,$x2,$y2,$text_color); // Drawing the line between two points//
}
$x1=$x2; // Storing the value for next draw
$y1=$y2;
$first_one="no"; // Now flag is set to allow the drawing
}
//header ("Content-Type: image/jpeg");
ImageJPEG ($im);
?>
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| adsf | 03-11-2014 |
| thanks you for usefull subjects | |