Fetch data from mysql database into datatable usin

2019-09-02 23:56发布

问题:

I have developed a mysql database and a php code. In php code i am using jQuery (ajax call) to fetch the data from the database. In html file i have printed datatable's table head only. Rest data i want to fetch from the database. code is given:


HTML CODE:

<div class="container box">
     <div class="table-responsive">
            <div id="alert_message"></div>
            <table id="example" class="display">
               <thead>
                  <tr>
                     <th>Student ID</th>
                     <th>Student Name</th>
                     <th>Email ID</th>
                     <th>Mobile</th>
                     <th>Status</th>
                  </tr>
               </thead>
            </table>
         </div>
      </div>

jQuery CODE:

<script>
    $(document).ready(function() {
        $('#example').dataTable({
            "processing": true,
            "serverSide": true,
            "ajax": {
                "url": "fetch.php",
                "type": "GET",
                "datatype": "json"
            }
        });
    });
</script>

fetch.php

<?php
$connect = mysqli_connect("localhost","root","","lib");
$sql = "SELECT StudentId, FullName, EmailId, MobileNumber, Status  FROM tblstudents";
$result = mysqli_query($connect,$sql);

$json_array = array();

while ($row = mysqli_fetch_assoc($result)) 
{
    $json_array[] = $row;
}

echo json_encode($json_array);
?>

Still the data is not printed in the datatable. What changes are necessary in jQuery?

回答1:

In jQuery Datatables, not only you can fetch data from ajax call. you can manage page ordering, searching as well.

first of all you have to modify your javascript like this.

$(document).ready(function() {
        $('#example').dataTable({
            "bProcessing": true,
            "serverSide": true,
            "ajax": {
                "url": "fetch.php",
                "type": "post"
            },
                error: function () {  // error handling code
                    $("#example").css("display", "none");
                }
        });
    });

Then as you can see in the browsers Developer Tools -> Network tap, all the parameters that wanted for searching, sorting and ordering will be pass trough the ajax call.

you can see it by print_r($_POST) in the ajax page (in your case fetch.php) and viewing it on ajax respond in the browsers Developer Tools -> Network tap.

you can collect all of that as follows,

    $order_by = $_POST['order']; // This array contains order information of clicked column
    $search = $_POST['search']['value']; // This array contains search value information datatable
    $start = $_POST['start']; // start limit of data
    $length = $_POST['length']; // end limit of data
    $order_type = $order_by[0]['dir'];
    if ($order_by[0]['column']==0){
        $order_column = "table_column_name_of_the_first_column_in_the_datatable";
    } elseif ($order_by[0]['column']==1){
        $order_column = "table_column_name_of_the_second_column_in_the_datatable";
    }

then you can construct the query as follows,

if ($search!='' || $search!=NULL) {
    $str = "WHERE column_name_to_search LIKE '%$search%' OR column_name_to_search LIKE '%$search%' ";
} else {
    $str = "";
}
$data[][] = array(); 
$i = 0;
$sql = $connection->query("SELECT * FROM your_table $str ORDER BY $order_column $order_type LIMIT $start,$length");
while ($row_1 = $sql->fetch_assoc()){
    $data[$i] = array($row_1['column_1'],$row_1['column_2']);
    $i++;
}

then to get total record count you can do as follows,

$sql_2 = $connection->query("SELECT COUNT(*) AS all_count FROM your_table $str");
$row_2 = $sql_2->fetch_assoc();
$totalRecords = $row_2['all_count'];
if ($totalRecords==0){
    $data = array();
}

finally construct the json out put that will be sent to the front view.

$json_data = array(
    "draw"            => intval( $_POST['draw'] ),
    "recordsTotal"    => intval( $totalRecords ),
    "recordsFiltered" => intval($totalRecords),
    "data"            => $data   // total data array
);
$json_data = json_encode($json_data);
echo $json_data;

That will work.



回答2:

I know this is really late, but I used the exact same code as you (thanks for that by the way!), and what made it work for me is to simply add to the JQuery code:

dataSrc = '' (after url = '...')

so that DataTables knows that it's loading an array. Putting that in made the code work fine!