DataTables server side proccessing warning - php

I am using DataTables, but it is causing an error, and I cannot find where the error is.
I want to use server-side processing, because after inserting 11k Rows, it's lagging.
The code I am using:
<?php
/* Database connection start */
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "accounts";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
/* Database connection end */
// storing request (ie, get/post) global array to a variable
$requestData= $_REQUEST;
$columns = array(
// datatable column index => database column name
0 =>'type',
1 => 'country',
2 => 'information',
3 => 'seller',
4 => 'price'
);
// getting total number records without any search
$sql = "SELECT type, country, information, seller, price ";
$sql.=" FROM accounts WHERE type2='1'";
$query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees");
$totalData = mysqli_num_rows($query);
$totalFiltered = $totalData; // when there is no search parameter then total number rows = total number filtered rows.
$sql = "SELECT type, country, information, seller, price ";
$sql.=" FROM accounts WHERE type2='1' AND 1=1";
if( !empty($requestData['search']['value']) ) { // if there is a search parameter, $requestData['search']['value'] contains search parameter
$sql.=" AND ( type LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR country LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR information LIKE '".$requestData['search']['value']."%' )";
$sql.=" OR seller LIKE '".$requestData['search']['value']."%' )";
}
$query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees");
$totalFiltered = mysqli_num_rows($query); // when there is a search parameter then we have to modify total number filtered rows as per search result.
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." ";
/* $requestData['order'][0]['column'] contains colmun index, $requestData['order'][0]['dir'] contains order such as asc/desc */
$query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees");
$data = array();
while( $row=mysqli_fetch_array($query) ) { // preparing an array
$nestedData=array();
$nestedData[] = $row["type"];
$nestedData[] = $row["country"];
$nestedData[] = $row["information"];
$nestedData[] = $row["seller"];
$nestedData[] = $row["price"];
$data[] = $nestedData;
}
$json_data = array(
"draw" => intval( $requestData['draw'] ), // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw.
"recordsTotal" => intval( $totalData ), // total number of records
"recordsFiltered" => intval( $totalFiltered ), // total number of records after searching, if there is no searching then totalFiltered = totalData
"data" => $data // total data array
);
echo json_encode($json_data); // send data as json format
?>
I am not finding any solutions.
The error that is showing on PHP file

$requestData does not have start and order keys, so use isset() or empty() functions to check if they are not empty, then only use them.
For example:
LIMIT " . (empty($requestData['start']) ?
'whatever you want to put default value' :
$requestData['start'])

Related

Datatables - Filter SQL results in server-side

I'm trying to create a filter in DataTables, but what I found is only filtering the data in "front end" (in the datatables script). I have 10K rows in the SQL table so I think, the "front end filtering/searching" is not my best option. I need to create a filter to my SQL Query in server-side, and get back only the filtered rows (datas).
Also the search option is not good option for me because I have in tables values like 1 or 2 (boolean).
My DataTables using this method (way) of fetching datas from SQL in backend:
include 'config.php';
## Read value
$draw = $_POST['draw'];
$row = $_POST['start'];
$rowperpage = $_POST['length']; // Rows display per page
$columnIndex = $_POST['order'][0]['column']; // Column index
$columnName = $_POST['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
$searchValue = $_POST['search']['value']; // Search value
$searchArray = array();
## Search
$searchQuery = " ";
if($searchValue != ''){
$searchQuery = " AND (emp_name LIKE :emp_name or
email LIKE :email OR
city LIKE :city ) ";
$searchArray = array(
'emp_name'=>"%$searchValue%",
'email'=>"%$searchValue%",
'city'=>"%$searchValue%"
);
}
## Total number of records without filtering
$stmt = $conn->prepare("SELECT COUNT(*) AS allcount FROM employee ");
$stmt->execute();
$records = $stmt->fetch();
$totalRecords = $records['allcount'];
## Total number of records with filtering
$stmt = $conn->prepare("SELECT COUNT(*) AS allcount FROM employee WHERE 1 ".$searchQuery);
$stmt->execute($searchArray);
$records = $stmt->fetch();
$totalRecordwithFilter = $records['allcount'];
## Fetch records
$stmt = $conn->prepare("SELECT * FROM employee WHERE 1 ".$searchQuery." ORDER BY ".$columnName." ".$columnSortOrder." LIMIT :limit,:offset");
// Bind values
foreach($searchArray as $key=>$search){
$stmt->bindValue(':'.$key, $search,PDO::PARAM_STR);
}
$stmt->bindValue(':limit', (int)$row, PDO::PARAM_INT);
$stmt->bindValue(':offset', (int)$rowperpage, PDO::PARAM_INT);
$stmt->execute();
$empRecords = $stmt->fetchAll();
$data = array();
foreach($empRecords as $row){
$data[] = array(
"emp_name"=>$row['emp_name'],
"email"=>$row['email'],
"gender"=>$row['gender'],
"salary"=>$row['salary'],
"city"=>$row['city']
);
}
## Response
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordwithFilter,
"aaData" => $data
);
echo json_encode($response);
In this code as you can see I have Search option, but as I said I can't use it for filtering columns with boolean values for example.
Another example what I want to do:
I have a column named by "edited" with boolean values.
How can I get those rows where the column "edited" have values 0?
I'm using MariaDB.
Thank you for your help!
You can easy write ...WHERE edited = :edited ... the value of edited should be 0 for false and 1 for true.
So in your example:
## Search
$searchQuery = " ";
if($searchValue != ''){
$searchQuery = " AND (emp_name LIKE :emp_name or
email LIKE :email OR
city LIKE :city ) AND
edited = :edited";
$searchArray = array(
'emp_name'=>"%$searchValue%",
'email'=>"%$searchValue%",
'city'=>"%$searchValue%",
'edited'=>$edited
);
}

Unable to use order and limit in Datatables server side using SQL server

I am encountering issue transferring my datatable server-side code from MySQL to SQL server. I have managed to display the output if I remove this particular line in the server side.
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." ";
But the issue is I can't order and limit the number of items appearing. How will I make this code work in SQL server? Please, any assistance would be a great help. Thank you
Here is my complete code for server side
<?php require_once("../includes/connection.php");
$connection = sqlsrv_connect(DB_HOST, array( 'Database'=>DB_NAME, 'UID'=>DB_USER, 'PWD'=>DB_PASSWORD,"CharacterSet" => "UTF-8"));
// /* Database connection end */
if( $connection ) {
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
// // storing request (ie, get/post) global array to a variable
$requestData= $_REQUEST;
$columns = array(
// datatable column index => database column name
0 =>'new_id',
1 => 'person_name',
2=> 'given_name',
3=> 'family_name'
);
// getting total number records without any search
$sql = "SELECT * , user.id as new_id ";
$sql.=" FROM user LEFT JOIN user_additional on user.doc_id = user_additional.doc_id LEFT JOIN users on users.id = user.user_name";
$query=sqlsrv_query($connection, $sql) ;
if( $query === false) {
die( print_r( sqlsrv_errors(), true) );
}
$totalData = sqlsrv_num_rows($query);
$totalFiltered = $totalData; // when there is no search parameter then total number rows = total number filtered rows.
$sql ="SELECT * , user.id as new_id ";
$sql.=" FROM user LEFT JOIN user_additional on user.doc_id = user_additional.doc_id LEFT JOIN users on users.id = user.user_name WHERE 1=1";
if( !empty($requestData['search']['value']) ) { // if there is a search parameter, $requestData['search']['value'] contains search parameter
$sql.=" AND ( person_name LIKE '%".$requestData['search']['value']."%' ";
$sql.=" OR family_name LIKE '%".$requestData['search']['value']."%' ";
$sql.=" OR given_name LIKE '".$requestData['search']['value']."%' )";
}
$query=sqlsrv_query($connection, $sql) ;
if( $query === false) {
die( print_r( sqlsrv_errors(), true) );
}
$totalFiltered = sqlsrv_num_rows($query); // when there is a search parameter then we have to modify total number filtered rows as per search result.
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." ";
/* $requestData['order'][0]['column'] contains colmun index, $requestData['order'][0]['dir'] contains order such as asc/desc */
$query=sqlsrv_query($connection, $sql) ;
if( $query === false) {
die( print_r( sqlsrv_errors(), true) );
}
$data = array();
while( $row=sqlsrv_fetch_array($query) ) { // preparing an array
$nestedData=array();
// $nestedData[]="";
$nestedData[] = $row["new_id"];
$nestedData[] = $row["person_name"];
$nestedData[] = $row["given_name"];
$nestedData[] = $row["family_name"];
;
$data[] = $nestedData;
}
$json_data = array(
"draw" => intval( $requestData['draw'] ), // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw.
"recordsTotal" => intval( $totalData ), // total number of records
"recordsFiltered" => intval( $totalFiltered ), // total number of records after searching, if there is no searching then totalFiltered = totalData
"data" => $data // total data array
);
echo json_encode($json_data); // send data as json format
?>
If you are using sql server 2012 or above you could use OFFSET/FETCH NEXT n ROWS ONLY clause. Sample query for your reference:
SELECT Id, FirstName, LastName, Dept
FROM Employee
order by Id asc
offset 100 rows
fetch next 10 rows only
Please try after modifying your code to build query as above. sample

Serverside datatable search show extra data

Hi I'm working on processing data in datatable using serverside processing. I've managed to show the data in the table but I haven't fully understood how it works with searches, I've included some code in the php file, but when I search for something with a where clause in the query it does show other values as well, this is my code for request.php
// storing request (ie, get/post) global array to a variable
$requestData = filter_var_array($_REQUEST);
$columns = array(
// datatable column index => database column name
0 => 'user_first',
1 => 'user_last',
2 => 'user_email',
);
// getting total number records without any search
$sql = "SELECT user_id, user_first, user_last, user_email, user_role";
$sql .=" FROM users WHERE user_role='partner'";
$query= mysqli_query($conn, $sql);
$totalData = mysqli_num_rows($query);
$totalFiltered = $totalData; // when there is no search parameter then total number rows = total number filtered rows.
if( !empty($requestData['search']['value']) ) {
// if there is a search parameter
$sql = "SELECT user_first, user_last, user_email";
$sql.=" FROM users WHERE user_role='partner'";
$sql.=" AND user_first LIKE '".$requestData['search']['value']."%' "; // $requestData['search']['value'] contains search parameter
$sql.=" OR user_last LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR user_email LIKE '".$requestData['search']['value']."%' ";
$query=mysqli_query($conn, $sql);
$totalFiltered = mysqli_num_rows($query); // when there is a search parameter then we have to modify total number filtered rows as per search result without limit in the query
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." "; // $requestData['order'][0]['column'] contains colmun index, $requestData['order'][0]['dir'] contains order such as asc/desc , $requestData['start'] contains start row number ,$requestData['length'] contains limit length.
$query=mysqli_query($conn, $sql); // again run query with limit
} else {
$sql = "SELECT user_first, user_last, user_email";
$sql.=" FROM users WHERE user_role='partner'";
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." ";
$query=mysqli_query($conn, $sql);
}
$data = array();
while( $row=mysqli_fetch_array($query) ) { // preparing an array
// Query al database per ottenere i gruppi a cui appartengono i condomini
$query_group_id = mysqli_prepare($conn, "SELECT group_name, group_id FROM user_group_join LEFT OUTER JOIN user_group ON user_group_join . group_join_id = user_group . group_id WHERE user_join_id = ?");
mysqli_stmt_bind_param($query_group_id, 'i', $row["user_id"]);
mysqli_stmt_execute($query_group_id);
mysqli_stmt_store_result($query_group_id);
mysqli_stmt_bind_result($query_group_id, $group_names, $group_ids);
$response=array();
while (mysqli_stmt_fetch($query_group_id)){
$response[]=$group_names;
}
$nestedData=array();
$nestedData[] = '<b><a onclick="ViewPartnerDetail('.$row["user_id"].')">'.ucfirst($row["user_first"]).' '.ucfirst($row["user_last"]).'</a></b>';
$nestedData[] = $row["user_email"];
$nestedData[] = '<select class="bs-select form-control show-menu-arrow"><option>'.implode("<option>",$response).'</option></select>';
$nestedData[] = '<button onclick="GetPartnerDetail('.$row["user_id"].')" class="btn btn-sm blue center"> <i class="fa fa-pencil-square-o"></i></button>';
$nestedData[] = '<button onclick="DeletePartner('.$row["user_id"].')" class="btn btn-sm red"> <i class="fa fa-trash-o"></i></button>';
$data[] = $nestedData;
}
$json_data = array(
"draw" => intval( $requestData['draw'] ), // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw.
"recordsTotal" => intval( $totalData ), // total number of records
"recordsFiltered" => intval( $totalFiltered ), // total number of records after searching, if there is no searching then totalFiltered = totalData
"data" => $data // total data array
);
echo json_encode($json_data); // send data as json format

Why it seems that the WHERE clause in my query doesn't work?

This code I'm using works fine but when I tried to query with a where clause, it looks like it doesn't work, it still displays all the data though I put a condition already. I also tried changing the way I put the where clause, but it says "no data found in the server" so I put the code back to its original form. I also tried putting a specific where clause like "where client = 'eadept'" but it still shows all details. This is my code.
session_start();
/* Database connection start */
$servername = "localhost";
$item = "root";
$password = "";
$dbname = "sample";
$conn = mysqli_connect($servername, $item, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
/* Database connection end */
// storing request (ie, get/post) global array to a variable
$requestData = $_REQUEST;
$columns = array(
// datatable column index => database column name
0 => 'facility',
1 => 'title',
2 => 'start',
3 => 'end',
4 => 'fee',
5 => 'status'
);
$uname = ($_SESSION['username']);
// getting total number records without any search
$sql = "SELECT facility, title, start, end, fee, status ";
$sql .= " FROM reservation WHERE client = '$uname'";
$query = mysqli_query($conn, $sql);
$totalData = mysqli_num_rows($query);
$totalFiltered = $totalData; // when there is no search parameter then total number rows = total number filtered rows.
$sql = "SELECT facility, title, start, end, fee, status ";
$sql .= " FROM reservation WHERE 1=1";
if(!empty($requestData['search']['value'])) { // if there is a search parameter, $requestData['search']['value'] contains search parameter
$sql .= " AND ( facility LIKE '" . $requestData['search']['value'] . "%' ";
$sql .= " OR title LIKE '" . $requestData['search']['value'] . "%' ";
$sql .= " OR fee LIKE '" . $requestData['search']['value'] . "%' )";
}
$query = mysqli_query($conn, $sql);
$totalFiltered = mysqli_num_rows($query); // when there is a search parameter then we have to modify total number filtered rows as per search result.
$sql .= " ORDER BY " . $columns[$requestData['order'][0]['column']] . " " . $requestData['order'][0]['dir'] . " LIMIT " . $requestData['start'] . " ," . $requestData['length'] . " ";
// $sql.="WHERE client = 'eadept'";
/* $requestData['order'][0]['column'] contains colmun index, $requestData['order'][0]['dir'] contains order such as asc/desc */
$query = mysqli_query($conn, $sql);
$data = array();
while($row = mysqli_fetch_array($query)) { // preparing an array
$nestedData = array();
$nestedData[] = $row["facility"];
$nestedData[] = $row["title"];
$nestedData[] = $row["start"];
$nestedData[] = $row["end"];
$nestedData[] = $row["fee"];
$nestedData[] = $row["status"];
$data[] = $nestedData;
}
$json_data = array(
"draw" => intval($requestData['draw']), // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw.
"recordsTotal" => intval($totalData), // total number of records
"recordsFiltered" => intval($totalFiltered), // total number of records after searching, if there is no searching then totalFiltered = totalData
"data" => $data // total data array
);
echo json_encode($json_data); // send data as json format
I'm referring to the query under the array. Can anyone please help and tell what to change so it will work?
I noticed that I'm just putting the query on a wrong place. This is the right code to do the WHERE clause.
$uname = ($_SESSION['username']);
// getting total number records without any search
$sql = "SELECT facility, item, start, end, fee, status ";
$sql.=" FROM reservation";
$query=mysqli_query($conn, $sql);
$totalData = mysqli_num_rows($query);
$totalFiltered = $totalData; // when there is no search parameter then total number rows = total number filtered rows.
$sql = "SELECT facility, item, start, end, fee, status ";
$sql.=" FROM reservation WHERE client = '$uname'";
if( !empty($requestData['search']['value']) ) { // if there is a search parameter, $requestData['search']['value'] contains search parameter
$sql.=" AND ( facility LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR item LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR fee LIKE '".$requestData['search']['value']."%' )";
// $sql.=" OR item LIKE '".$requestData['search']['value']."%' )";
// $sql.=" OR start LIKE '".$requestData['search']['value']."%' )";
// $sql.=" OR end LIKE '".$requestData['search']['value']."%' )";
// $sql.=" OR fee LIKE '".$requestData['search']['value']."%' )";
// $sql.=" OR status LIKE '".$requestData['search']['value']."%' )";
}
$query=mysqli_query($conn, $sql);
$totalFiltered = mysqli_num_rows($query); // when there is a search parameter then we have to modify total number filtered rows as per search result.
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." ";
// $sql.="WHERE client = 'eadept'";
/* $requestData['order'][0]['column'] contains colmun index, $requestData['order'][0]['dir'] contains order such as asc/desc */
$query=mysqli_query($conn, $sql);

datatables + lengthMenu + All + serverside processing + handling -1/All

this is a basic datatables fiddle
this is a basic datatables fiddle with lengthMenu
What I want to do is get this working in my serverside processing example.
I can get the dropdown to appear right doing the following to my index.php file.
$(document).ready(function() {
var dataTable = $('#employee-grid').DataTable({
"lengthMenu": [
[10, 25, 50, -1],
[10, 25, 50, "All"]
],
"processing": true,
"serverSide": true,
"ajax": {
url: "employee-grid-data.php", // json datasource
type: "post", // method , by default get
error: function() { // error handling
$(".employee-grid-error").html("");
$("#employee-grid").append('<tbody class="employee-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
$("#employee-grid_processing").css("display", "none");
}
}
});
});
So that works okay if I select 10, 25 or 50 but if I select All I get No data found in the server.
So my issue is in my employee-grid-data.php file,noted here, and this is where I am having my difficulty. I need to do an if statement to handle this All option or -1 as this is what I pass to the server when I select All in $requestData['length']
I have identified the 2 areas where I use $requestData['length'] and this I belive to be the issue.
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." "; // $requestData['order'][0]['column'] contains colmun index, $requestData['order'][0]['dir'] contains order such as asc/desc , $requestData['start'] contains start row number ,$requestData['length'] contains limit length.
$query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees"); // again run query with limit
So what I have to do is try and write such that:
if $requestData['length'] NOT equals -1
do this line
else
do this line without using $requestData['length'] as a parameter.
This is where I am having difficulty.
This is my attempt, but this could be a syntax issue or something else. I'm not very good at debugging this.
if ($requestData['length']!==-1){
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." ";
} else {
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']
}
$query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees");
When I visit the page index.php I get No data found in the server and in the console I get 500 (Internal Server Error).
Can anyone advise what my code should look like?
Or how could I debug this?
I would ideally like to be able to add a basic if else statement just to see if I could get that bit right alone, but not sure how to do this in this setup. with Javasecript I would normally use console.log
Here is my entire employee-grid-data.php file for reference:
<?php
/* Database connection start */
$servername = "localhost";
$username = "root";
$password = "Password1";
$dbname = "test";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
/* Database connection end */
// storing request (ie, get/post) global array to a variable
$requestData= $_REQUEST;
$columns = array(
// datatable column index => database column name
0 =>'employee_name',
1 => 'employee_salary',
2=> 'employee_age'
);
// getting total number records without any search
$sql = "SELECT employee_name, employee_salary, employee_age ";
$sql.=" FROM employee";
$query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees");
$totalData = mysqli_num_rows($query);
$totalFiltered = $totalData; // when there is no search parameter then total number rows = total number filtered rows.
if( !empty($requestData['search']['value']) ) {
// if there is a search parameter
$sql = "SELECT employee_name, employee_salary, employee_age ";
$sql.=" FROM employee";
$sql.=" WHERE employee_name LIKE '".$requestData['search']['value']."%' "; // $requestData['search']['value'] contains search parameter
$sql.=" OR employee_salary LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR employee_age LIKE '".$requestData['search']['value']."%' ";
$query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees");
$totalFiltered = mysqli_num_rows($query); // when there is a search parameter then we have to modify total number filtered rows as per search result without limit in the query
if ($requestData['length']!==-1){
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." "; // $requestData['order'][0]['column'] contains colmun index, $requestData['order'][0]['dir'] contains order such as asc/desc , $requestData['start'] contains start row number ,$requestData['length'] contains limit length.
} else {
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']
}
$query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees"); // again run query with limit
} else {
$sql = "SELECT employee_name, employee_salary, employee_age ";
$sql.=" FROM employee";
if ($requestData['length']!==-1){
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." ";
} else {
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']
}
$query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees");
}
$data = array();
while( $row=mysqli_fetch_array($query) ) { // preparing an array
$nestedData=array();
$nestedData[] = $row["employee_name"];
$nestedData[] = $row["employee_salary"];
$nestedData[] = $row["employee_age"];
$data[] = $nestedData;
}
$json_data = array(
"draw" => intval( $requestData['draw'] ), // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw.
"recordsTotal" => intval( $totalData ), // total number of records
"recordsFiltered" => intval( $totalFiltered ), // total number of records after searching, if there is no searching then totalFiltered = totalData
"data" => $data // total data array
);
echo json_encode($json_data); // send data as json format
?>
edit1 good link for testing http://phpfiddle.org/
This is the code I had to add to handle the $requestData['length'] equaling -1. I had to add wherever I had $requestData['length']. This is the best I could do.
if ($requestData['length'] > 0 ){
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." ";
} else {
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." ";
}

Categories