Most enterprise apps currently use relational databases like SQL, MariaDB, or MySQL due to their popularity and stable nature. However, developers face issues when they try to scale such databases. Furthermore, considering the recent breed of web applications that handle large data sets, developers are constantly looking for more scalable databases. This has attributed to the rise of non-relational (NoSQL) databases. One such database that has become really popular is MongoDB.
In this tutorial we will follow a step-by-step approach to create charts using data stored in a MongoDB database. We will use the PHP scripting language to connect to the database and fetch the data, which would then be used to render the chart.
We picked PHP over other similar languages because it comes with a MongoDB driver that connects it to the database. If you need to add more firepower in your web application, you can also use Node.js.
For creating charts using PHP and MongoDB, you need the following to be downloaded and installed on your system:
To render FusionCharts in PHP using MongoDB, we need to include the following dependencies:
1<html>
2 <head>
3 <!-- including FusionCharts core package JS files -->
4 <script src="path-to/fusioncharts.js"></script>
5 <script src="path-to/fusioncharts.theme.fint.js"></script>
6 </head>
7</html>
fusioncharts.php
file inside the same folder created in the previous step for keeping the script files.1<?php
2 // including FusionCharts PHP wrapper
3 require 'fusioncharts/fusioncharts.php';
4?>
autoload.php
file that is required for using MongoDB with PHP.1<?php
2 require 'vendor\autoload.php';
3?>
Once we've added dependencies, we can establish the connection with our database to fetch data for the chart.
1<?php
2$dbconn = new MongoDB\Client;
3
4// validating DB connection
5if(!$dbconn) {
6 exit("There was an error establishing database connection");
7}
8?>
Now that we have established the connection to our database, we will fetch data for our chart.
Here's quick look at our chartData
collection in myProject
database which we will be using to render the chart.
Given below is the PHP code for fetching data from our database:
1// retrieving data from the database
2$db = $dbconn->myProject;
3$myObj = $db->chartData->find();
4
5//convert MongoCursor into an array
6$data=iterator_to_array($myObj);
7
8// sorting the data
9asort($data);
After the above code is executed successfully, $data
will hold data fetched from our database. We will now form an associative JSON array for the chart.
FusionCharts understands both XML and JSON data formats. Since we will be using JSON, we will now append the data (fetched from database in the $data
variable) along with FusionCharts chart configuration and parse the end result as an associative JSON array.
Given below is the PHP code needed to append the chart data fetched from the database:
1if ($data) {
2
3 $categoryArray=array();
4
5 $dataseries1=array();
6
7 $dataseries2=array();
8
9 foreach ($data as $dataset) {
10 array_push($categoryArray, array(
11 "label" => $dataset["month"]
12 ));
13
14 array_push($dataseries1, array(
15 "value" => $dataset["petrol"]
16 ));
17
18 array_push($dataseries2, array(
19 "value" => $dataset["diesel"]
20 ));
21 }
22
23
24 $arrData = array(
25 "chart" => array(
26 "caption"=> "Comparison of Petrol and Diesel price",
27 "xAxisname"=>"Month",
28 "yAxisname"=>"Price",
29 "numberPrefix"=>"$",
30 "paletteColors"=> "#876EA1, #72D7B2",
31 "useplotgradientcolor"=> "0",
32 "plotBorderAlpha"=> "0",
33 "bgColor"=> "#FFFFFFF",
34 "canvasBgColor"=> "#FFFFFF",
35 "showValues"=> "0",
36 "showCanvasBorder"=> "0",
37 "showBorder"=> "0",
38 "divLineAlpha"=> "40",
39 "divLineColor"=> "#DCDCDC",
40 "alternateHGridColor"=> "#DCDCDC",
41 "alternateHGridAlpha"=> "15",
42 "labelDisplay"=> "auto",
43 "baseFont"=> "Assistant",
44 "baseFontColor"=> "#000000",
45 "outCnvBaseFont"=> "Assistant",
46 "outCnvBaseFontColor"=> "#000000",
47 "baseFontSize"=> "13",
48 "outCnvBaseFontSize"=> "13",
49 "labelFontColor"=> "#000000",
50 "captionFontColor"=> "#153957",
51 "captionFontBold"=> "1",
52 "captionFontSize"=> "20",
53 "subCaptionFontColor"=> "#153957",
54 "subCaptionfontSize"=> "17",
55 "subCaptionFontBold"=> "0",
56 "captionPadding"=> "20",
57 "valueFontBold"=> "0",
58 "showAxisLines"=> "1",
59 "yAxisLineColor"=> "#DCDCDC",
60 "xAxisLineColor"=> "#DCDCDC",
61 "xAxisLineAlpha"=> "15",
62 "yAxisLineAlpha"=> "15",
63 "toolTipPadding"=> "7",
64 "toolTipBorderColor"=> "#DCDCDC",
65 "toolTipBorderThickness"=> "0",
66 "toolTipBorderRadius"=> "2",
67 "showShadow"=> "0",
68 "toolTipBgColor"=> "#153957",
69 "toolTipBgAlpha"=> "90",
70 "toolTipColor"=> "#FFFFFF",
71 "legendBorderAlpha"=> "0",
72 "legendShadow"=> "0",
73 "legendItemFontSize"=> "14"
74 )
75 );
76
77 $arrData["categories"]=array(array("category"=>$categoryArray));
78
79 // creating dataset object
80 $arrData["dataset"] = array(array("seriesName"=> "Petrol_price", "data"=>$dataseries1), array("seriesName"=> "Diesel_price", "data"=>$dataseries2));
81
82 $jsonEncodedData = json_encode($arrData);
83
84}
Every chart displayed on a web page is rendered within a unique HTML container. We will be using the <div>
element for creating the HTML container for our chart.
Given below is the code for creating the chart container:
1<body>
2 <div id="chart-container">Fusion Charts will render here</div>
3</body>
Now that we have the JSON data and chart container in place, we will create the FusionCharts instance and call render method to render the chart.
Chart instance includes details needed to render the chart, like the chart type, chart ID, chart dimensions, the HTML container ID, and so on, will be passed to this chart instance.
1$msChart = new FusionCharts("msline", "demochart", "600", "400", "chart-container", "json", $jsonEncodedData);
2
3$msChart->render();
If you have followed the above steps, then you should have a working chart with you now. Your output should be like the image shown below:
If you are having trouble rendering the chart, you can download the source code from this GitHub repo.
Got questions? Feel free to say hi on Twitter! Thank you for reading!