DataTable using PHP

What is DataTable?
DataTable is a JQuery Plugin which provides in-built features like Searching, Sorting, Pagination.

The main advantage of using DataTable is that we do not have to write seperate code for Pagination, Search, Sort when displaying dynamic data.

How to Use DataTable Plugin in PHP?

Integrating DataTable Plugin using PHP is very simple. You can follow below steps and implement it :

1. Import DataTable CDN :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>  
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>            
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />  

2. Connect to Database

<?php
$connection = mysqli_connect("localhost","root","","mydb");
?>

3. Using Select Query & While Loop Fetch and Display Dynamic Data in Table Format

<?php
$query = mysqli_query($connection,"select * from users");

?>
<table>
<thead>
<tr>
<td>Name</td>
<td>Mobile</td>
</tr>
</thead>
<?php
// data dynamically show
while($k = mysqli_fetch_assoc($query))
{
?>
<tr>
<td><?php echo $k['name']; ?></td>
<td><?php echo $k['mobile']; ?></td>
</tr>
<?php
}
?>
</thead>
</table>

4. Assign a ID inside <table> tag

<table id="myTable" >

5. Using JQuery, call DataTable() Function
<script>  
 $(document).ready(function(){  
      $('#myTable').DataTable();  
 });  
 </script>

Now, summarizing the entire code once :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>  
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>            
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />  

<!-- db connection -->
<?php
$connection = mysqli_connect("localhost","root","",",mydb");

// show data in table format
$query = mysqli_query($connection,"select * from users");

?>
<table id="myTable" border="2" width="100%">
<thead>
<tr>
<td>Name</td>
<td>Mobile</td>
</tr>
</thead>
<?php
// data dynamically show
while($k = mysqli_fetch_assoc($query))
{
?>
<tr>
<td><?php echo $k['name']; ?></td>
<td><?php echo $k['mobile']; ?></td>
</tr>
<?php
}
?>
</thead>
</table>

<script>  
 $(document).ready(function(){  
      $('#myTable').DataTable();  
 });  
 </script> 
 

Comments