Bind jQuery Grid to MySql Database using PHP

In this post we will show you how to connect our jQuery Grid to MySql Database using PHP. We will obtain the data from MySql Database and especially the Northwind Database. You can download the Northwind database .sql script here and run it into MySQL to create the database.

The first thing we need to do is create the file we’ll connect with. We’ll call this file connect.php.

<?php
# FileName="connect.php"
$hostname = "localhost";
$database = "customers";
$username = "root";
$password = "";
?>

Now we have our file to do the connection for us and we need to create the file that will run the query and bring the data so our Grid can be populated. We will call the file data.php.

<?php
#Include the connect.php file
include('connect.php');
#Connect to the database
//connection String
$connect = mysql_connect($hostname, $username, $password)
or die('Could not connect: ' . mysql_error());
//select database
mysql_select_db($database, $connect);
//Select The database
$bool = mysql_select_db($database, $connect);
if ($bool === False){
   print "can't find $database";
}
// get data and store in a json array
$query = "SELECT * FROM customers";
$from = 0;
$to = 30;
$query .= " LIMIT ".$from.",".$to;

$result = mysql_query($query) or die("SQL Error 1: " . mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
	$customers[] = array(
        'CompanyName' => $row['CompanyName'],
        'ContactName' => $row['ContactName'],
	'ContactTitle' => $row['ContactTitle'],
	'Address' => $row['Address'],
	'City' => $row['City']
      );
}

echo json_encode($customers);
?>

The data is returned as JSON. This is it for the connection and data gathering. Let’s see how to add the data we just gathered into our jQuery Grid. Create the index.php file and add references to the following javascript and css files.

<link rel="stylesheet" href="styles/jqx.base.css" type="text/css" />
<link rel="stylesheet" href="styles/jqx.classic.css" type="text/css" />
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="jqxcore.js"></script>
<script type="text/javascript" src="jqxbuttons.js"></script>
<script type="text/javascript" src="jqxscrollbar.js"></script>
<script type="text/javascript" src="jqxmenu.js"></script>
<script type="text/javascript" src="jqxgrid.js"></script>

Create a div tag for the Grid.

<div id="jqxgrid"></div>

Create your grid and load the data. We define a source object for the Grid and bind that source to the data.php which returns the JSON data. We are also defining the Grid columns for the CompanyName, ContactName, ContactTitle, Address and City.

   <script type="text/javascript">
        $(document).ready(function () {
            // prepare the data
            var source =
            {
                datatype: "json",
                datafields: [
                    { name: 'CompanyName'},
                    { name: 'ContactName'},
                    { name: 'ContactTitle'},
                    { name: 'Address'},
                    { name: 'City'},
                ],
                url: 'data.php'
            };

            $("#jqxgrid").jqxGrid(
            {
                source: source,
                theme: 'classic',
                columns: [
                  { text: 'Company Name', datafield: 'CompanyName', width: 250},
                  { text: 'ContactName', datafield: 'ContactName', width: 150 },
                  { text: 'Contact Title', datafield: 'ContactTitle', width: 180 },
                  { text: 'Address', datafield: 'Address', width: 200 },
                  { text: 'City', datafield: 'City', width: 120 }
              ]
            });
        });
    </script>

The result is a nice looking jQuery Grid.

Binding jQuery Grid to JSON Data

Today, we will show you how to bind the jQuery Grid, called jqxGrid to a JSON data.

Below is a sample JSON data that we want to use as a data source. In this post, we will assume that this data is in a file called beverages.txt.

[{
 "id": "1",
 "name": "Hot Chocolate",
 "type": "Chocolate Beverage",
 "calories": "370",
 "totalfat": "16g",
 "protein": "14g"
 }, {
 "id": 2,
 "name": "Peppermint Hot Chocolate",
 "type": "Chocolate Beverage",
 "calories": "440",
 "totalfat": "16g",
 "protein": "13g"
}, {
 "id": "3",
 "name": "Salted Caramel Hot Chocolate",
 "type": "Chocolate Beverage",
 "calories": "450",
 "totalfat": "16g",
 "protein": "13g"
}, {
 "id": "4",
 "name": "White Hot Chocolate",
 "type": "Chocolate Beverage",
 "calories": "420",
 "totalfat": "16g",
 "protein": "12g"
}, {
 "id": "5",
 "name": "Caffe Americano",
 "type": "Espresso Beverage",
 "calories": "15",
 "totalfat": "0g",
 "protein": "1g"
}, {
 "id": "6",
 "name": "Caffe Latte",
 "type": "Espresso Beverage",
 "calories": "190",
 "totalfat": "7g",
 "protein": "12g"
}, {
 "id": "7",
 "name": "Caffe Mocha",
 "type": "Espresso Beverage",
 "calories": "330",
 "totalfat": "15g",
 "protein": "13g"
}, {
 "id": "8",
 "name": "Cappuccino",
 "type": "Espresso Beverage",
 "calories": "120",
 "totalfat": "4g",
 "protein": "8g"
}, {
 "id": "9",
 "name": "Caramel Brulee Latte",
 "type": "Espresso Beverage",
 "calories": "420",
 "totalfat": "9g",
 "protein": "8g"
}, {
 "id": "10",
 "name": "Caramel Macchiato",
 "type": "Espresso Beverage",
 "calories": "240",
 "totalfat": "11g",
 "protein": "10g"
}, {
 "id": "11",
 "name": "Peppermint Hot Chocolate",
 "type": "Espresso Beverage",
 "calories": "440",
 "totalfat": "10g",
 "protein": "13g"
}, {
 "id": "12",
 "name": "Cinnamon Dolce Latte",
 "type": "Espresso Beverage",
 "calories": "260",
 "totalfat": "6g",
 "protein": "10g"
}, {
 "id": "13",
 "name": "Eggnog Latte",
 "type": "Espresso Beverage",
 "calories": "460",
 "totalfat": "16g",
 "protein": "13g"
}]

To initialize the Grid, we need to add the references to the javascript and css files.

<link rel="stylesheet" href="styles/jqx.base.css" type="text/css" />
<link rel="stylesheet" href="styles/jqx.classic.css" type="text/css" />
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="jqxcore.js"></script>
<script type="text/javascript" src="jqxbuttons.js"></script>
<script type="text/javascript" src="jqxscrollbar.js"></script>
<script type="text/javascript" src="jqxmenu.js"></script>
<script type="text/javascript" src="jqwidgets/jqxgrid.js"></script>

Add a div tag to the document’s body. The div tag will be used for the Grid widget.

<div id="jqxgrid"></div>

Now, lets create the ‘data’ object. We want to bind the Grid to JSON data, so we set the ‘datatype’ member to ‘json’. The ‘url’ member points to the url where the beverages.txt file is. The ‘datafields’ array member represents the Grid columns definitions. Each member should have ‘name’ and optionally a ‘type’ member such as ‘int’, ‘float’, ‘date’, and ‘bool’.

// prepare the data
var data =
{
    datatype: "json",
    datafields: [
        { name: 'name'},
        { name: 'type'},
        { name: 'calories'},
        { name: 'totalfat'},
        { name: 'protein'},
    ],
    id: 'id',
    url: "beverages.txt"
};

Populate the Grid. Select the ‘jqxgrid’ element and call the jqxGrid constructor. In the constructor, set the source property to the ‘data’ object and create the grid columns. The ‘text’ member specifies the text displayed in the column’s header and the ‘datafield’ member associates the grid column(ex: ‘Name’) to the data column(ex: ‘name’).

$("#jqxgrid").jqxGrid(
{
    source: data
    theme: 'classic',
    columns: [
        { text: 'Name', datafield: 'name', width: 250},
        { text: 'Beverage Type', datafield: 'type', width: 250 },
        { text: 'Calories', datafield: 'calories', width: 180 },
        { text: 'Total Fat', datafield: 'totalfat', width: 120 },
        { text: 'Protein', datafield: 'protein', width: 120 }
    ]
});