PHPGraphLib Tutorial #4: Passing Parameters to a Graph Script

Overview

This is a variation of tutorial 1, except this time we're going to pass data to the graph by appending a GET param to the image script filename.

Include the source file "phpgraphlib.php" in a new script

To include the source PHPGraphLib class file, add this php include call at the top of your stand alone php script. This script will only include the PHP calls to create your graph. You will not include any HTML output in this script. Later, we will set the src="" element of an html image tag to the location of our new script on the desired page for our graph.

<?php
include("phpgraphlib.php"); 

Creating the PHPGraphLib Object

Next, you have to create a PHPGraphLib object. You may leave the arguments blank to use default dimensions, or you may specify your own width and height.

$graph=new PHPGraphLib(400,300);

Add data to the graph from a passed data parameter

To add data to the graph, call the addData() function on your PHPGraphLib object. You must specify an array as the argument to the addData() function as shown below. The values in the array will be used as y-axis values. If the array has keys, the keys will be used as x axis values.

You can pass data into a PHPGraphLib script by specifying a $_GET parameter. We'll see how to pass in the data a little later, but below is how you would retrieve an array of serialized data passed in with the $_GET parameter of mydata.

$data = unserialize(urldecode(stripslashes($_GET['mydata'])));
$graph->addData($data);

Customize the graph

In this example we have decided to give the graph a title, and set the y-axis values to be the color red. By default, all PHPGraphLib graphs are bar graphs, so we do not have to call anything special to display this.

$graph->setTitle("Test Scores");
$graph->setTextColor("blue");

After all customizations are done, we call the createGraph() function to finalize the graph. Now, you can close the php script and include the "?>" php tag.

$graph->createGraph();
?>

Here is the whole script we created above:

<?php
include("phpgraphlib.php");
$graph=new PHPGraphLib(400,300);
$data = unserialize(urldecode(stripslashes($_GET['mydata'])));
$graph->addData($data);
$graph->setTitle("Test Scores");
$graph->setTextColor("blue");
$graph->createGraph();
?>

Include the created script as the src of an image and pass data in via a GET param

On the page you want the graph to appear, create an HTML image tag and set the src="" to the location of the script you created above. To pass in data we need to add GET params to the end of the filename with our data variable

<?php
$data = array("Alex"=>99, "Mary"=>98, "Joan"=>70, "Ed"=>90);
?>
<html>
<h3>This is where I want to display my graph</h3>
<img src="graph_bar.php?mydata=<?php echo urlencode(serialize($data)); ?>" />
</html>

You're done! Here is the graph you just created:

For more advanced examples, view the Examples page