Bind jQuery Grid to MySql Database using PHP

In this help topic, 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.

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.

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.11.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="jqxdata.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.

$(document).ready(function () {
// prepare the data
var source ={
datatype: "json",
datafields: [{ name: 'CompanyName' },{ name: 'ContactName' },{ name: 'ContactTitle' },{ name: 'Address' },{ name: 'City' },],
url: 'data.php'
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 }]