Jquery DataTables is a powerful jQuery plugin for creating table, listings and adding interactions to them. It provides searching, sorting and pagination without any configuration. In this article we will go through the basics of DataTable and how to use some of the features.


Getting started

DataTables can work with data from a verity of sources. It can directly work on an HTML table or we can specify data as an array while initialization. Or it can work on data coming from an Ajax source. Let’s see the DataTables can do with a minimal setup.
<html>
<head>
  <link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
</head>
<body>
  <table id="example">
    <thead>
      <tr><th>Sites</th></tr>
    </thead>
    <tbody>
      <tr><td>mysite.com</td></tr>
      <tr><td>mgnad.com</td></tr>
      <tr><td>gforgadget.com</td></tr>
    </tbody>
  </table>
  <script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>
  <script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
  <script>
  $(function(){
    $("#example").dataTable();
  })
  </script>
</body>
</html>

PHP :


<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.18/datatables.min.css"/>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>

<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.18/datatables.min.js"></script>



<?php

//database connection
        $dbhost = "localhost";
        $username = "databaseUserName";
        $password = "password";
        $dbname = "databasename";
       
$conn = mysqli_connect($dbhost, $username, $password, $dbname);
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
else{
    echo "connected";
}

After the successful Database Connection :


$sql = "SELECT * FROM table_name";

$result = $conn->query($sql);

if ($result->num_rows > 0) {

?>

<table id="demoTable">

          <thead>
<tr>             //Table row
<th> login ip adress </th>  //Table Headings
</tr>
         </thead>
         <tbody>
         <?php  
          while($row = $result->fetch_assoc()) {   //fetching data by loop
         ?>
         <tr>
         <td> <?php echo $row['login_ip']; ?> </td> //Table data
         </tr>        
         <?php
         }  //while closing
         ?>
         </tbody>
         </table>
         <?php
         } // If closing
         else{
         echo "0 results"; // If table does not contain data
         }
         ?>
<script type="text/javascript">
    $(document).ready( function () {
    $('#demoTable').DataTable();
} );
</script>

Note : To use Jquery DataTables <thead> </thead>  and  <tbody> </tbody> is maditory.


Post a Comment

Previous Post Next Post