FusionCharts and PHP> Using dataURL method
 

Here, we'll be using PHP as our choice of scripting language and create the dynamic "Top 5 Countries" 3D column chart, with MS SQL Server as our database, using the dataURL method. We'll be using VB.NET as our choice of .NET language.

Please do read the section "Using with scripts and database", if you've not already read, before reading this section.

As we had earlier seen, the dataURL method requires two pages:

  • Chart Container Page - This page contains the chart object alongwith any other HTML objects. We'll name this page as Chart.php - in this page, we let the user select the year for which he wants to view the chart and would show the chart.
  • Data Provider Page - This page provides the XML data required by the chart. This page is invoked by FusionCharts contained in Chart.php. We'll name this page as Data.php.

The above two are present in the downloads under the folder FusionCharts2_3 > Sample Code > DBExamples > PHP > dataURL.

We'll also need two other pages:

  • Connection_ini.php- This page contains the data connection details.
  • FC_Colors.php - This page contains a list of hex colors (without #) in an array named as strColor.

The above two include files are present under FusionCharts2_3 > Sample Code > DBExamples > PHP folder.

FC_Colors.php looks as under:

<?php
$strColor[0] = 'AFD8F8';
$strColor[1] = 'F6BD0F';
$strColor[2] = '8BBA00';
$strColor[3] = 'A66EDD';
$strColor[4] = 'F984A1';
$strColor[5] = 'CCCC00'; #Chrome Yellow+Green
$strColor[6] = '999999'; #Grey
$strColor[7] = '0099CC'; #Blue Shade
$strColor[8] = 'FF0000'; #Bright Red
$strColor[9] = '006F00'; #Dark Green
$strColor[10] = '0099FF'; #Blue (Light)
$strColor[11] = 'FF66CC'; #Dark Pink
$strColor[12] = '669966'; #Dirty green
$strColor[13] = '7C7CB4'; #Violet shade of blue
$strColor[14] = 'FF9933'; #Orange
$strColor[15] = '9900FF'; #Violet
$strColor[16] = '99FFCC'; #Blue+Green Light
$strColor[17] = 'CCCCFF'; #Light violet
$strColor[18] = '669900'; #Shade of green
$strColor[19] = '1941A5'; #Dark Blue
?>

Basically, this file is a list of hex colors that we'll be using for the chart. In the above list, we've stored only 20 colors. You can extend it to any number. You should note that all the above colors are without the #. We'll include this file in all our pages, where we generate the XML data for FusionCharts.
 

Connection_ini.php is the page which contains the database connection details. When you run the code on your machine, after downloading the package, you should ensure that this page is updated so as to reflect the connection details to your SQL server. This page looks as under:

<?php
$dsn="Northwind";
$username="sa";
$password="sa";
?>

 
The page Data.php is responsible for relaying virtual XML documents to the FusionCharts embedded in Chart.php. You should note that Data.php does NOT write XML data documents to the server disk physically. It relays the XML data document virtually (i.e., no XML files are created and saved on the server). The code for this page can be reproduced as under:
<?php
   //Include connection and colors file
   include '../FC_Colors.php';
   include '../Connection_ini.php';

   //Connect to the ODBC Source
   $sqlconnect=odbc_connect($dsn,$username,$password);

   //strSQL - String variable to contain the SQL query
   $strSQL="SELECT TOP 5 Country, SUM(ExtendedPrice) As Total, COUNT(DISTINCT OrderID) As orderNumber FROM Invoices WHERE YEAR(OrderDate)=" . $_GET["year"] . " GROUP BY Country ORDER BY SUM(ExtendedPrice) DESC";

   //strXMLDataData - String variable to contain the entire XML data document for the chart
   //Initialize the <graph> element.

   $strXMLData = "<graph caption='Top 5 Countries for the Year " . $_GET["year"] . "' shownames='1' showvalues='0' decimalPrecision='0' numberPrefix='$'>" . chr(13);

   $intCounter=0;
   //Get the recordset
   $oRs=odbc_exec($sqlconnect, $strSQL);

   //Iterate through each row to get the data
   while(odbc_fetch_row($oRs)) {
      //Append the value in format <set name='...' value='...' color='...' />
      $strXMLData = $strXMLData . "<set name='" . odbc_result($oRs,"Country") . "' color='" . $strColor[$intCounter] . "' value='" . odbc_result($oRs,"Total") . "'/>" . chr(13);
      //Increment the counter
      $intCounter=$intCounter+1;
   }
   odbc_close($sqlconnect);

   //Entire XML - concatenation
   $strXMLData = $strXMLData . "</graph>";

   //Write the XML data to output stream
   echo trim($strXMLData);
?>

In the above code, we're doing the following:

  1. We first request the year, for which we have to show the data. The year was passed in the format Data.php?year=1996 (or 1997 or 1998) by the FusionCharts charts contained in the page Chart.php
  2. We initialize a variable strXMLData which would store the entire XML data document. We initialize the <graph> element in this string variable.
  3. Next, we retrieve the recordset from the database and iterate through the records one by one. For each record, we add a <set> element in the format <set name='DataName' value='DataValue' color='HexCode' />. We get individual color codes for each data item from the list of colors that we had stored in the array strColor (stored in FC_Colors.php).
  4. Thereafter, we add the ending </graph> element to the XML document (stored as string in strXMLData),
  5. In the end, we just write this XML data document to the output stream.

When you try viewing this page individually in the browser (in the format http://localhost/...Path.../DBExamples/PHP/dataURL/Data.php?year=1996), you'll get the following XML output. You should always make sure, that while using dataURL method, your dataURL script should output just XML data and no HTML tags.

<graph caption='Top 5 Countries for the Year 1996' shownames='1' showvalues='0' decimalPrecision='0' numberPrefix='$'>
   <set name='USA' value='38105.68' color='AFD8F8'/>
   <set name='Germany' value='35407.15' color='F6BD0F'/>
   <set name='Austria' value='25601.34' color='8BBA00'/>
   <set name='Brazil' value='20148.82' color='A66EDD'/>
   <set name='France' value='17372.76' color='F984A1'/>
</graph>

This is exactly the XML that we need for our 3D Column Chart. So, let's now shift our attention to Chart.php and see the code it contains to attain the following tasks:

  1. Present the list of unique years in a drop down list to the user - so that the end user can select the year for which the chart should appear.
  2. Embed the FusionCharts Chart in the PHP page and convey dataURL in the format Data.php?year=199x

Chart.php contains the following code:

<HTML>
<HEAD>
<TITLE>FusionCharts</TITLE>
<LINK REL='Stylesheet' HREF='../Style.css'>
</HEAD>
<?php
   //Include connection and colors file
   include '../Connection_ini.php';
   include '../FC_Colors.php';

   //Connect to the ODBC Source
   $sqlconnect=odbc_connect($dsn,$username,$password);

   //Generate the query to get a list of unique years
   $strSQL="SELECT DISTINCT YEAR(OrderDate) As Year FROM Orders ORDER BY 1";

   //Get the list of years
   $oRsYears=odbc_exec($sqlconnect, $strSQL);

   //If an year has been selected
   if ($_POST) {
      $intYear = $_POST['year'];
   }
   else {
      //By default select the last year.
      while(odbc_fetch_row($oRsYears)){
         $intYear = odbc_result($oRsYears,"Year");
      }
   }
   //Define dataURL
   $strDataURL = "Data.php?year=" . $intYear;
   //URL Encode the dataURL - Important Step
   $strDataURL = urlencode($strDataURL);
?>
<table width="500" border="0" cellpadding="2" cellspacing="0" class="tableWithBorder" align='center'>
<tr>
<td colspan="3" class="trdark"><div align="center"><span class="textboldlight">FusionCharts</span></div></td>
</tr>
<form action="Chart.php" method="post">
<tr>
<td colspan="3" class="text" align="center">Please select the year for which you want to see the chart:
<SELECT name='year' class='select' onChange="this.form.submit();">
<?
   //Get back to start position

   $oRsYears=odbc_exec($sqlconnect, $strSQL);
   while(odbc_fetch_row($oRsYears)){
      echo("<option value='" . odbc_result($oRsYears,"Year") . "'");
      if (odbc_result($oRsYears,"Year")==$intYear){
         echo(" selected");
      }
      echo(" >" . odbc_result($oRsYears,"Year"));
   }
?>

</SELECT>
</td>
</tr>
</form>
<tr>
<td colspan="3">&nbsp;</td>
</tr>
<tr>
<td valign="top">
<table width="98%" border="0" cellspacing="0" cellpadding="2" align='center'>
<tr>
<td>
<div align="center" class="text">
<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" WIDTH="450" HEIGHT="300" id="FusionCharts" ALIGN="">
<PARAM NAME="FlashVars" value="&dataURL=<?=$strDataURL?>">
<PARAM NAME=movie VALUE="../../../Charts/FC_2_3_Column3D.swf?chartWidth=450&chartHeight=300">
<PARAM NAME=quality VALUE=high>
<PARAM NAME=bgcolor VALUE=#FFFFFF>
<EMBED src="../../../Charts/FC_2_3_Column3D.swf?chartWidth=450&chartHeight=300" FlashVars="&dataURL=<?=$strDataURL?>" quality=high bgcolor=#FFFFFF WIDTH="450" HEIGHT="300" NAME="FusionCharts" ALIGN="" TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"></EMBED>
</OBJECT>
</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
<p align="center" class="text">&copy;All Rights Reserved - InfoSoft Global Private Limited - 2005 - <a href="http://www.InfoSoftGlobal.com" target="_blank">www.InfoSoftGlobal.com</a></p>
</BODY></html>

Here, in the above code, we're doing the following:

  1. First, we're requesting a list of unique years from the database and rendering them in a drop down box. By default, we choose the last year as the selected year (i.e., the year for which we'll show the chart) and store it in the variable intYear. When the user selects a different year from the drop down box, the forms submits to this page only and the new requested year is stored in the variable intYear.
  2. Next, we generate the dataURL string in the format Data.php?year=(intYear) (i.e., Data.php?year=1996)
  3. Thereafter, we embed the FusionCharts chart in this page and provide the above dataURL to it (see the code in bold above).

When you now see Chart.php in your browser, you'll get the following output: