简体   繁体   中英

Datatables Server side processing very slow

I am using Datatables server side processing using PHP, Jquery, Ajax and my database in SQL Server.

The data is displayed correctly in a table But the features like pagination and search are very slow. Everytime I type in seach box or i change pagination to next page I am waiting more than 40 seconds although i am not dealing with large data.

Here is my index page

<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html" charset=utf-8" />
  <title> Datatables using PHP Ajax Jquery </title>

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap.min.css">

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap.min.js"></script>


 </head>
 <body>
  <div class="container">
    <div class="table-responsive">
      <table id="example" class="table table-striped table-bordered" style="width:100%">
        <thead>
            <tr>
                <th>Country</th>
                <th>Customer</th>
                <th>Address</th>
                <th>Contact</th>
                <th>Price</th>
                <th>Qty</th>
            </tr>
        </thead>
      </table>
   </div>
  </div>
 </body>
</html>

<script type="text/javascript" language="javascript" >
$(document).ready(function() {
            $('#example').DataTable({
            "columns": [
                {"data": "Country"},
                {"data": "Customer"},
                {"data": "Address"},
                {"data": "Contact"},
                {"data": "Price"},
                {"data": "Qty"}
            ],
            "processing": true,
            "serverSide": true,
            "ajax": {
                url: 'fetch.php',
                type: 'POST'
            }
        });
} );
</script>

and here is my fetch.php where is the Ajax call

<?php 
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (!empty($_POST) ) {

$ser="****";
$db="****";
$user="****"; 
$pass="****";
$MyTable="****";

$dbDB = new PDO("odbc:Driver=ODBC Driver 13 for SQL Server;Server=****;Database=****", $user, $pass);


    function getData($sql){
        global $dbDB ;
        global $MyTable ;
        $result = $dbDB->query($sql);
        $rows = $result->fetchAll(PDO::FETCH_ASSOC);
        $data = array();
        foreach ($rows as $row) {
        $data[] = $row ; }
        return $data; }

    $draw = $_POST["draw"];
    $orderByColumnIndex  = $_POST['order'][0]['column'];
    $orderBy = $_POST['columns'][$orderByColumnIndex]['data'];
    $orderType = $_POST['order'][0]['dir']; 
    $start  = $_POST["start"];
    $length = $_POST['length'];

    $recordsTotal = count(getData("SELECT * FROM ".$MyTable));

    if(!empty($_POST['search']['value'])){

        for($i=0 ; $i<count($_POST['columns']);$i++){
            $column = $_POST['columns'][$i]['data'];
            $where[]="$column like '%".$_POST['search']['value']."%'";
        }
        $where = "WHERE ".implode(" OR " , $where);

        $sql = sprintf("SELECT * FROM %s %s", $MyTable , $where);
        $recordsFiltered = count(getData($sql));

         $sql = sprintf("SELECT Country,Customer,Address,Contact,Price,Qty FROM %s %s ORDER BY %s %s OFFSET %d ROWS FETCH NEXT %d ROWS ONLY", $MyTable , $where ,$orderBy, $orderType ,$start,$length);
         $data = getData($sql);
    }

    else {
        $sql = sprintf("SELECT Country,Customer,Address,Contact,Price,Qty FROM %s ORDER BY %s %s OFFSET %d ROWS FETCH NEXT %d ROWS ONLY", $MyTable ,$orderBy, $orderType ,$start,$length);
        $data = getData($sql);
        $recordsFiltered = $recordsTotal;
    }

        $response = array(
        "draw" => intval($draw),
        "recordsTotal" => $recordsTotal,
        "recordsFiltered" => $recordsFiltered,
        "data" => $data
    );

    echo json_encode($response);

} 

else {
    echo "NO POST Query from DataTable";
}

?>

I don't understand why the search and pagination are very slow when i use server side processing. I checked some options in datatables documentation but it didn't speed up the loading time.

any ideas please where could be the issue ? Thank you very much.

It's just guessing (ie there might be some weird javascript library that's nuking your loading times), but it probably has to do with these lines:

$recordsTotal = count(getData("SELECT * FROM ".$MyTable));

$recordsFiltered = count(getData($sql));

You're selecting everything from the database and then proceed to count those rows with PHP. A database can do this infinitely faster with the COUNT function.

Also, the optimum path for your code involves 2 database queries. The other requires 3 queries, from which 2 are incredibly heavy on performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM