Categories: Tutorials

Create Charts using PHP and MongoDB

PHP is one of the most widely used server side languages. We’ve already got detailed documentation on how PHP can be easily integrated with FusionCharts using the FusionCharts-PHP wrapper. We also had a recent blog post on how you can use the Zend Framework (a cluster of PHP packages) with FusionCharts. PHP is fairly easy to work with, w.r.t its support for many database technologies. However, there is some work involved when using PHP with a NoSQL database. However, before we move to talking about that, it is important that we brush up on what is NoSQL, for there will be many of us who aren’t familiar with this database technology. Let’s first talk about:
  • What is NoSQL?
  • Why people use NoSQL?
Here goes the answers… NoSQL also referred to as ‘NOT ONLY SQL’ or ‘non relational’ database, provides a data storage and retrieval mechanism that is modeled differently from the traditional tabular relations that are used in relational databases. NoSQL is used because it encompasses a wide variety of different database technologies that were developed in response to the demands presented in building modern applications. Top NoSQL databases used today include MongoDB, Redis, Cassandra, CouchDB HBase, Neo4j, and so on. In this blog post, we’ll explore how to integrate PHP with MongoDB and create a chart using FusionCharts. MongoDB is an open-source, document-oriented database developed by MongoDB Inc. It works on the concept of document and collections, stores data in the JSON format, and can vary in structure as per the requirement. Query access is fast through the MongoDB Query Language. It uses dynamic schemas, meaning that you can create records without first defining the structure, such as the fields or the type of values.

Now that we have the basics sufficiently covered, let’s get started…

To get the code in this blog working, we need to install the following components: Make sure that all the above mentioned components are present in the system and are working as expected.

Next, we move on to how you can create the database

Step 1: Execute the command “mongod” using the shell to run the mongodb server. Step 2: Create a json file that contains the data that goes into the database and will used as the source data for the chart. We’ll name this file as fuel_price.json.
[
  {
    "month": "Jan", "petrol" : 64.72, "diesel": 52.49
  },
  {
    "month": "Feb", "petrol" : 62.81, "diesel": 50.72
  },
  {
    "month": "Mar", "petrol" : 66.18, "diesel": 54.06
  },
  {
    "month": "Apr", "petrol" : 65.17, "diesel": 51.74
  },
  {
    "month": "May", "petrol" : 72.94, "diesel": 57.23
  },
  {
    "month": "Jun", "petrol" : 73.77, "diesel": 55.83
  },
  {
    "month": "Jul", "petrol" : 70.7, "diesel": 52.59
  },
  {
    "month": "Aug", "petrol" : 66.72, "diesel": 47.54
  },
  {
    "month": "Sept", "petrol" : 64.61, "diesel": 47.02
  }
]
Step 3: Import the .json file created in Step 2 into mongodb using the command shown below.
mongoimport -d database_name -c collection_name –type json –file complete path for the json file –jsonArray
Step 4: Next, open another shell to run the command “mongo”. Now we need to verify if our data has been imported correctly into the database or no. To do this, you need to execute the following commands:
  • Use the “show dbs” command to see your database. A list of the databases present is shown.
  • From this list, select the required database using the “use database_name” command.
  • Next, use the “show collections” command, which shows the collections inside your database.
  • For seeing the contents of a specific collection, execute the “db.collection_name.find()” command .
With this, we are done with creating the database. Now lets move to the coding part that is a three-step process with, multiple sub-steps.

STEP I (Configuration)

Create a file and save it as config.php inside the project folder.
  • Include the ‘autoload.php’ file that is required for using mongodb with php.
    require 'vendor\autoload.php';
  • Next, we need to create the connection between php and mongoDB.
    $connection = new MongoDB\Client;
After completion of the configuration, the php code will look like this.
 

STEP II

  • Extract the FusionCharts Suite XT zip and keep all the script files in a new folder inside the project folder, as shown below. Here, we have named the new folder as fusioncharts.
  • Extract the fusioncharts PHP wrapper and keep the fusioncharts.php file inside the same folder created in the previous step for keeping the script files (for our example, fusioncharts).

STEP III (Main Page)

  • Create a file multiseries_mongodb.php, because we will be creating a multi-series chart using mongodb. Include the config.php file inside this file, using the command shown below:
    require 'config.php';
  • Include the ‘fusioncharts.php’ file that contains functions to embed fusioncharts in php.
    include("fusioncharts/fusioncharts.php")
  • Add the fusioncharts script file.
    <hepad>
            <script src="fusioncharts/fusioncharts.js"></script>
             <script src="fusioncharts/fusioncharts.theme.fint.js"></script>
        </hepad>
  • Retrieve data from the database: Include the php code within the body tag. First, retrieve the data from the database and store it in a variable. Here we are storing the data in a variable called $myObj.
    myProject;
    $myObj = $db->chartData->find();
    ?>
    Here chartData is the collection name in the database myProject.
  • Form an associative array: As $myObj is a mongo cursor, we need to convert it to an associative array.
    //convert mongoCursor into an array
        $data=iterator_to_array($myObj);
    Thereafter, sort the associative array in an ascending order (if required).
    asort($data);
  • Next, we will create an array that will contain the dataset—the chart attributes and the data—fetched from the database.
    $categoryArray=array();
                $dataseries1=array();
                $dataseries2=array();
                foreach ($data as $dataset) {
                        array_push($categoryArray, array(
                          "label" => $dataset["month"]
                        )
                    );
                    array_push($dataseries1, array(
                        "value" => $dataset["petrol"]
                        )
                    );
                    array_push($dataseries2, array(
                        "value" => $dataset["diesel"]
                        )
                    );
                }
    $arrData = array(
                "chart" => array(
                    "caption"=> "Comparison of Petrol and Diesel price",
                    "xAxisname"=> "Month",
                    "yAxisName"=> "Price",
                    "plotFillAlpha"=> "80",
                    "showValues"=> "0",
                    "bgcolor"=>"#89C3C4",
                    "canvasbgcolor"=>"#A0CBC2",
                    "paletteColors"=> "#00B1C1,#0184B8",
                    "baseFont"=> "Open Sans",
                    "showPlotBorder"=>"1",
                    "theme" => "fint"
                    )
                );
                $arrData["categories"]=array(array("category"=>$categoryArray));
                        // creating dataset object
                $arrData["dataset"] = array(array("seriesName"=> "Petrol_price", "data"=>$dataseries1), array("seriesName"=> "Diesel_price",  "renderAs"=>"line", "data"=>$dataseries2)); 
  • The associative array created in the above step will now have to be encoded into a json format that is required to render the chart.
    $jsonEncodedData = json_encode($arrData);
  • Now, we create the chart object and render the chart using render() function.
    $msChart = new FusionCharts("msline","chart1" , "100%", "400", "chart-container", "json", $jsonEncodedData);
    
    $msChart->render();
  • Next, we close the php tag and continue with the html part by defining the dom element, where the chart will render.
    <div id="chart-container">Fusion Charts will render here</div>
  • Finally, execute the php code using any browser. eg. https://localhost/phpMongodb/multiSeries_mongodb.php Your output should be like the image shown below:
If you see any errors in your code, click here to download the complete source code of the sample project we have created for this tutorial.
Dishank Tiwari and Prerana Singh

Recent Posts

Announcing FusionCharts v4.1: Elevate Your Data Visualization Experience!

We’re excited to announce the upcoming release of FusionCharts v4.1—a groundbreaking step forward in the…

5 days ago

Bubble Maps: Visualizing Data Like Never Before

Have you ever been overwhelmed by a massive data set and wondered, "How do I…

2 weeks ago

Stock Charts: Mastering the Art of Visualizing Financial Data

If you’ve ever tried to make sense of the stock market, you’ve probably come across…

4 weeks ago

What is a Bar Chart Used For?

Imagine you’re comparing the sales performance of your top product lines across different regions, or…

2 months ago

AI-Powered Documentation for Data Visualization & Analytics

Have you ever spent hours buried in documentation, hunting for a specific piece of code?…

3 months ago

Unveiling the Hidden Gems: Top 5 AI Data Visualization Tools for 2024

Do you feel like your data is a cryptic puzzle, locked away from revealing its…

4 months ago