Sort DateTime field of a DataTable - php

I am having problems sorting the DateTime field of a DataTable, I am returning records from my customers table via server-side. The problem is when it is time to click on the label of a column of type DateTime, the data is ordered as if it were String and not as DateTime. I need in the Brazilian format: DD/MM/YYYY
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Customers</title>
</head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<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>
<body>
<h2>Customers</h2>
<table id="server-side" class="table table-striped table-bordered table-hover" width="100%" cellspacing="0">
<thead>
<tr>
<th>ID</th>
<th>REGISTER</th>
<th>NAME</th>
<th>LEVEL</th>
<th>OPTIONS</th>
</tr>
</thead>
</table>
<script>
$(document).ready(function(e){
$('#server-side').dataTable({
"bProcessing": true,
"serverSide": true,
"aoColumnDefs": [
{
"bSearchable": false,
"bVisible": false,
"aTargets": [0]
},
{
"aTargets": [4],
"mRender": function ( data, type, full ) {
return '<i class="fa fa-eye"></i> VIEW '+
'<i class="fa fa-pencil"></i> EDIT '+
'<i class="fa fa-trash"></i> DELETE';
}
}
],
language: {
processing: "processing...",
},
"ajax":{
url :"server-side.php",
type: "POST",
error: function(){
$("#post_list_processing").css("display","none");
}
},
"order": [ 1, "desc"],
});
});
</script>
</body>
</html>
server-side.php
<?php
$host = 'db_host';
$db = 'db_name';
$user = 'db_user';
$pass = 'db_password';
$con = mysqli_connect($host, $user, $pass) or trigger_error(mysql_error(),E_USER_ERROR);
$con->set_charset("utf8");
mysqli_select_db($con,$db);
$params = $columns = $totalRecords = $data = array();
$params = $_REQUEST;
$columns = array(
0 => 'id',
1 => 'register',
2 => 'name',
3 => 'level'
);
$where_condition = $sqlTot = $sqlRec = "";
if( !empty($params['search']['value']) ) {
$where_condition .= " WHERE ";
$where_condition .= " ( name LIKE '%".$params['search']['value']."%' ";
$where_condition .= " OR register LIKE '%".$params['search']['value']."%' )";
}
$sql_query = "SELECT id,date_format(register, '%d/%m/%Y') as register,name,level FROM customers";
$sqlTot .= $sql_query;
$sqlRec .= $sql_query;
if(isset($where_condition) && $where_condition != '') {
$sqlTot .= $where_condition;
$sqlRec .= $where_condition;
}
$sqlRec .= " ORDER BY ". $columns[$params['order'][0]['column']]." ".$params['order'][0]['dir']." LIMIT ".$params['start']." ,".$params['length']." ";
$queryTot = mysqli_query($con, $sqlTot) or die("Database Error:". mysqli_error($con));
$totalRecords = mysqli_num_rows($queryTot);
$queryRecords = mysqli_query($con, $sqlRec) or die("Error to Get the Post details.");
while( $row = mysqli_fetch_row($queryRecords) ) {
$data[] = $row;
}
$json_data = array(
"draw" => intval( $params['draw'] ),
"recordsTotal" => intval( $totalRecords ),
"recordsFiltered" => intval($totalRecords),
"data" => $data
);
echo json_encode($json_data);
?>

You could format your date in PHP, and use the initial date format to sort with MySQL.
// Remove format here,
$sql_query = "SELECT id,register,name,level FROM customers";
Then, format your date in while loop:
while( $row = mysqli_fetch_row($queryRecords) ) {
$row['register'] = date('d/m/Y', strtotime($row['register']));
$data[] = $row;
}

Related

Data doesn't fetch from the Database using DataTable

I am new to jQuery DataTable. Here just I am trying to get the records from the database using DataTable. Also I am using a custom filter for advance searching option.
But the case is records doesn't fetch from the database. It always shows in the bottom of the table like: Showing 0 to 0 of 0 entries (filtered from 2 total entries). Nothing error occurred while processing.
Here is the HTML code.
<div class="col-sm-4">
<div class="form-group">
<label>Enter Appointment Date </label>
<input class="form-control" type="date" id="dates" name="dates">
<span id="type" class="info text-danger"></span><br />
</div>
</div>
<table id="example" style="width:100%" class="table table-hover">
<thead>
<tr>
<th>Apt ID</th>
<th>Doctor</th>
<th>Specialist</th>
<th>Patient</th>
<th>Type</th>
<th>Apt.Date</th>
<th>Status</th>
<th>Change</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<th>Apt ID</th>
<th>Doctor</th>
<th>Specialist</th>
<th>Patient</th>
<th>Type</th>
<th>Apt.Date</th>
<th>Status</th>
<th>Change</th>
<th>Action</th>
</tr>
</tbody>
</table>
Here is the query;
$(document).ready(function () {
fill_datatable();
function fill_datatable(dates = '')
{
var dataTable = $('#example').DataTable({
"processing" : true,
"serverSide" : true,
"order" : [],
"searching" : false,
"ajax" : {
url:"adminquery/fetch/appointment/fetch_appointment.1.php",
type:"POST",
data:{
dates:dates
}
}
});
}
$('#dates').change(function(){
var dates = $('#dates').val();
if(dates != '')
{
$('#example').DataTable().destroy();
fill_datatable(dates);
}
else
{
$('#example').DataTable().destroy();
fill_datatable();
}
});
Below is the fetch.php
$conn = new PDO("mysql:host=localhost;dbname=hmsproject", "root", "");
$columns= array('apt_id','username','specilization','patient_name','type','apt_date','admin_status','Change');
// $query = "SELECT * FROM appointment as a,users as u WHERE a.user_id= u.user_id";
$query = " SELECT * FROM appointment as a INNER JOIN doctor_schedule as d ON a.user_id=d.user_id";
if(isset($_POST['dates'] ))
{
$query .= 'AND a.apt_date = "'.$_POST['dates'].'"
';
}
if(isset($_POST['order']))
{
$query .= 'ORDER BY '.$column[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY No DESC ';
}
$query1 = '';
if($_POST["length"] != -1)
{
$query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $conn->prepare($query);
$statement->execute();
$number_filter_row = $statement->rowCount();
$statement = $conn->prepare($query . $query1);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
foreach($result as $row)
{
$sub_array = array();
$sub_array[] = $row['apt_id'];
$sub_array[] = $row['doctor_name'];
$sub_array[] = $row['specilization'];
$sub_array[] = $row['patient_name'];
$sub_array[] = $row['type'];
$sub_array[] = $row['apt_date'];
$sub_array[] =' <span class="custom-badge status-red">Cancelled</span>';
$data[] = $sub_array;
}
function count_all_data($conn)
{
$query = "SELECT * FROM appointment as a INNER JOIN doctor_schedule as d ON a.user_id=d.user_id";
$statement = $conn->prepare($query);
$statement->execute();
return $statement->rowCount();
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => count_all_data($conn),
"recordsFiltered" => $number_filter_row,
"data" => $data
);
echo json_encode($output);
The debug shows like:
{draw: 1, recordsTotal: 2, recordsFiltered: 0, data: []} data: []
draw: 1 recordsFiltered: 0 recordsTotal: 2
I don't know where I went wrong. Actually I am new to this. Any help may highly appreciated.
is your connection query is right?
see you should not directly use ajax data / datatables >>> first of all see what output your page generating in your case check : url:"adminquery/fetch/appointment/fetch_appointment.1.php"
and use static values for Data table, if both working fine then only go further

Jquery server side processing data table with one extra column as link with row id?

I am doing server side pagination with jquery data table and php as server side.
What I need is I want an extra column header as download with data as a link with respective to its id. for example: Download .
Below is my HTML code:
<table id="employee_grid" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>Empid</th>
<th>Name</th>
<th>Salary</th>
<th>Age</th>
</tr>
</thead>
</table>
My Js:
$('#employee_grid').DataTable({
"bProcessing": true,
"serverSide": true,
"ajax":{
url :"response.php", // json datasource
type: "post", // type of method ,GET/POST/DELETE
error: function(){
$("#employee_grid_processing").css("display","none");
}
}
});
});
My PHP:
<?php
//include connection file
include_once("connection.php");
// initilize all variable
$params = $columns = $totalRecords = $data = array();
$params = $_REQUEST;
//define index of column
$columns = array(
0 =>'id',
1 =>'employee_name',
2 => 'employee_salary',
3 => 'employee_age'
);
$where = $sqlTot = $sqlRec = "";
// check search value exist
if( !empty($params['search']['value']) ) {
$where .=" WHERE ";
$where .=" ( employee_name LIKE '".$params['search']['value']."%' ";
$where .=" OR employee_salary LIKE '".$params['search']['value']."%' ";
$where .=" OR employee_age LIKE '".$params['search']['value']."%' )";
}
// getting total number records without any search
$sql = "SELECT * FROM `employee` ";
$sqlTot .= $sql;
$sqlRec .= $sql;
//concatenate search sql if value exist
if(isset($where) && $where != '') {
$sqlTot .= $where;
$sqlRec .= $where;
}
$sqlRec .= " ORDER BY ". $columns[$params['order'][0]['column']]." ".$params['order'][0]['dir']." LIMIT ".$params['start']." ,".$params['length']." ";
$queryTot = mysqli_query($conn, $sqlTot) or die("database error:". mysqli_error($conn));
$totalRecords = mysqli_num_rows($queryTot);
$queryRecords = mysqli_query($conn, $sqlRec) or die("error to fetch employees data");
//iterate on results row and create new index array of data
while( $row = mysqli_fetch_row($queryRecords) ) {
$data[] = $row;
}
$json_data = array(
"draw" => intval( $params['draw'] ),
"recordsTotal" => intval( $totalRecords ),
"recordsFiltered" => intval($totalRecords),
"data" => $data // total data array
);
echo json_encode($json_data); // send data as json format
?>
I have tried using column render and several other things but doesn't able to make out.
Any help?
To achieve this you will need to use columnDefs and column.render options.
https://datatables.net/reference/option/columnDefs
https://datatables.net/examples/advanced_init/column_render.html
You should be able to render your rows by adding this to your DataTable initialisation:
"columnDefs": [
{
"render": function ( data, type, row ) {
let rowID = row[0];
return `Download`
},
"targets": 4
}
]
You also need to add new column to html
<table id="employee_grid" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>Empid</th>
<th>Name</th>
<th>Salary</th>
<th>Age</th>
<th>Download</th>
</tr>
</thead>
</table>

Ajax MYSQL search and sorting results

Trying to find out how to add sort option of my mysql results that are fetched with Ajax functionality. Sorting by mysql columns or something. Below are some "th" sections where I would like to have sorting options implemented.
HTML page
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Tool details</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<input type="text" name="search_text" id="search_text" placeholder="Search for tool details" class="form-control" />
<div id="result"></div>
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
success:function(data) {
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search != '') {
load_data(search);
} else {
load_data();
}
});
});
</script>
</body>
</html>
Please not that sorting is added only for ID column at the moment to avoid complicating code here.
fetch.php
<?php
//fetch.php
include($_SERVER['DOCUMENT_ROOT'].'/db/connect-db.php');
$output = '';
if(isset($_POST["query"])) {
$search = mysqli_real_escape_string($connection, $_POST["query"]);
$query = "SELECT * FROM tools
WHERE toolsn LIKE '%".$search."%'
OR toolcategory LIKE '%".$search."%'
OR tooldesc LIKE '%".$search."%'
OR toolpn LIKE '%".$search."%'
OR toolstatus LIKE '%".$search."%'";
} else {
$query = "SELECT * FROM tools ORDER BY id";
}
$result = mysqli_query($connection, $query);
//get feedback why database not working
if (!$result) {
printf("Error: %s\n", mysqli_error($connection));
exit();
}
if(mysqli_num_rows($result) > 0) {
$output .= '
<div class="table-responsive">
<table class="table table bordered">
<tr>
<th>Customer Name</th>
<th>Address</th>
<th>City</th>
<th>Postal Code</th>
<th>Country</th>
</tr>';
while($row = mysqli_fetch_array($result)) {
$output .= '<tr>
<td>'.$row["tooldesc"].'</td>
<td>'.$row["toolcategory"].'</td>
<td>'.$row["toolsn"].'</td>
<td>'.$row["toolpn"].'</td>
<td>'.$row["toolstatus"].'</td>
</tr>';
}
echo $output;
}else {
echo 'Data Not Found';
}
?>
I have managed to reproduce sorting option with below code, but this works only if I directly access fetch.php page.
When I tried to fetch details through my html page (over the script) only results are shown, but without sorting function (hyperlinks are not working)
Probably because below code cant read two strings because fetch.php is included in parent html page.
$query = "SELECT * FROM tools ORDER BY " . $orderBy . " " . $order;
so $orderby and $order are not giving command to $query because it is not directly accessed page. Script from html page is reading results from fetch.php.
fetch.php
<?php
//fetch.php
include($_SERVER['DOCUMENT_ROOT'].'/db/connect-db.php');
$orderBy = "id";
$order = "asc";
if(!empty($_GET["orderby"])) {
$orderBy = $_GET["orderby"];
}
if(!empty($_GET["order"])) {
$order = $_GET["order"];
}
$idNextOrder = "asc";
$tooldescNextOrder = "asc";
$toolcategoryNextOrder = "asc";
$toolsnNextOrder = "asc";
$toolpnNextOrder = "asc";
$toolstatusNextOrder = "asc";
if($orderBy == "id" and $order == "asc") {
$idNextOrder = "desc";
}
if($orderBy == "tooldesc" and $order == "asc") {
$tooldescNextOrder = "desc";
}
if($orderBy == "toolcategory" and $order == "asc") {
$toolcategoryNextOrder = "desc";
}
if($orderBy == "toolsn" and $order == "asc") {
$toolsnNextOrder = "desc";
}
if($orderBy == "toolpn" and $order == "asc") {
$toolpnNextOrder = "desc";
}
if($orderBy == "toolstatus" and $order == "asc") {
$toolstatusNextOrder = "desc";
}
$output = '';
if(isset($_POST["query"]))
{
$search = mysqli_real_escape_string($connection, $_POST["query"]);
$query = "
SELECT * FROM tools
WHERE toolsn LIKE '%".$search."%'
OR toolcategory LIKE '%".$search."%'
OR tooldesc LIKE '%".$search."%'
OR toolpn LIKE '%".$search."%'
OR toolstatus LIKE '%".$search."%'
";
}
else
{
//$query = "SELECT * FROM tools";
$query = "SELECT * FROM tools ORDER BY " . $orderBy . " " . $order;
}
$result = mysqli_query($connection, $query);
//get feedback why database not working
if (!$result) {
printf("Error: %s\n", mysqli_error($connection));
exit();
}
if(mysqli_num_rows($result) > 0)
{
$output .= '
<div class="table-responsive">
<table class="table table bordered">
<tr>
<th class="id"><a title="Sort by system ID" href="?orderby=id&order='.$idNextOrder.'">ID</a></th>
<th class="toolsn"><a title="Sort by tool serial number" href="?orderby=toolsn&order='.$toolsnNextOrder.'">Tool SN</a></th>
<th class="toolpn"><a title="Sort by tool part number" href="?orderby=toolpn&order='.$toolpnNextOrder.'">Tool PN</a></th>
<th class="toolcategory"><a title="Sort by tool category" href="?orderby=toolcategory&order='.$toolcategoryNextOrder.'">Tool category</a></th>
<th class="tooldesc"><a title="Sort by tool description" href="?orderby=tooldesc&order='.$tooldescNextOrder.'">Tool description</a></th>
<th class="toolstatus"><a title="Sort by tool status" href="?orderby=toolstatus&order='.$toolstatusNextOrder.'">Tool status</a></th>
<th class="options"></th>
</tr>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["id"].'</td>
<td>'.$row["toolsn"].'</td>
<td>'.$row["toolpn"].'</td>
<td>'.$row["toolcategory"].'</td>
<td>'.$row["tooldesc"].'</td>
<td>'.$row["toolstatus"].'</td>
<td></td>
</tr>
';
}
echo $output;
}
else
{
echo 'Data Not Found';
}
?>

DataTable fetch modified data from row

I have a problem with printing the right content from a row in my datatble.
i have a file called response.php with the following content:
//include connection file
session_start();
include_once("connection.php");
// initilize all variable
$params = $columns = $totalRecords = $data = array();
$params = $_REQUEST;
//define index of column
$columns = array(
0 =>'log_in_timestamp',
1 =>'liDateInserted',
2 => 'browser',
3 => 'location',
4 => 'lo_li_time'
);
$where = $sqlTot = $sqlRec = "";
// check search value exist
if( !empty($params['search']['value']) ) {
$where .=" WHERE ";
$where .=" ( browser LIKE '".$params['search']['value']."%' ";
$where .=" OR location LIKE '".$params['search']['value']."%' ";
$where .=" AND ut.id = '".$_SESSION["userSession"]."%' ";
}
// getting total number records without any search
$sql = "SELECT li.log_in_timestamp, li.date_inserted liDateInserted, li.browser, li.location, (lo.log_out_timestamp - li.log_in_timestamp) lo_li_time, li.user_who_used_the_session, li.id historyId,
lo.id, lo.user_who_used_the_session, lo.log_out_timestamp, lo.date_inserted, ut.id, ut.username
FROM log_in_user_sessions li
LEFT JOIN log_out_user_sessions lo ON li.unique_id_login = lo.unique_id_logout
LEFT JOIN user_table ut ON li.user_who_used_the_session = ut.username
WHERE ut.id = '".$_SESSION["userSession"]."'";
$sqlTot .= $sql;
$sqlRec .= $sql;
//concatenate search sql if value exist
if(isset($where) && $where != '') {
$sqlTot .= $where;
$sqlRec .= $where;
}
$sqlRec .= " ORDER BY ". $columns[$params['order'][0]['column']]." ".$params['order'][0]['dir']." LIMIT ".$params['start']." ,".$params['length']." ";
$queryTot = mysqli_query($conn, $sqlTot) or die("database error:". mysqli_error($conn));
$totalRecords = mysqli_num_rows($queryTot);
$queryRecords = mysqli_query($conn, $sqlRec) or die("error to fetch employees data");
//iterate on results row and create new index array of data
while( $row = mysqli_fetch_row($queryRecords) ) {
$data[] = $row;
}
$json_data = array(
"draw" => intval( $params['draw'] ),
"recordsTotal" => intval( $totalRecords ),
"recordsFiltered" => intval($totalRecords),
"data" => $data // total data array
);
echo json_encode($json_data); // send data as json format
now in my index.php
i call the table like this:
<div class="container">
<div class="">
<h3>User Sessions</h3><br>
<div class="">
<table id="employee_grid" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>Time</th>
<th>Date</th>
<th>Browser</th>
<th>Location</th>
<th>Duration</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Time</th>
<th>Date</th>
<th>Browser</th>
<th>Location</th>
<th>Duration</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
i've tried the js like this:
<script type="text/javascript">
$( document ).ready(function() {
$('#employee_grid').DataTable({
"bProcessing": true,
"serverSide": true,
"columnDefs": [
{ "width": "20%", "defaultContent": "Not Logged Out","targets": "_all" }
],
"fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
// Bold the grade for all 'A' grade browsers
if (!aData[4])
{
$(nRow).addClass( 'alert-danger' ).css('background-color', '#f2dede');
}
},
"lengthMenu": [[5, 10, 25, 50, -1], [5, 10, 25, 50, "All"]],
"responsive": true,
"ajax":{
url :"../test/dt/dt_i/response.php",
type: "post",
error: function() {
$("#employee_grid_processing").css("display", "none");
}
}
});
});
</script>
my output looks like this:
i've created the same thing for my own in php and it looks like this. I want the DataTable to look like this:
i've tried to get my knowledge from here, here or here
My question now is, how can i output the right formatted data like the unixtimestamp with the right css background in my 2nd picture
Edit:
i changed my sql statement to:
SELECT FROM_UNIXTIME(li.log_in_timestamp, '%H:%i'), DATE(li.date_inserted) liDateInserted, li.browser, li.location, FROM_UNIXTIME((lo.log_out_timestamp - li.log_in_timestamp), '%H:%i:%sh') lo_li_time, li.user_who_used_the_session, li.id historyId,
lo.id, lo.user_who_used_the_session, lo.log_out_timestamp, lo.date_inserted, ut.id, ut.username
FROM log_in_user_sessions li
LEFT JOIN log_out_user_sessions lo ON li.unique_id_login = lo.unique_id_logout
LEFT JOIN user_table ut ON li.user_who_used_the_session = ut.username
WHERE ut.id = '" . $_SESSION["userSession"] . "'
and now everything is correctly formatted, but with the css-background is still a problem...
Can someone correct this lines here ?:
"fnRowCallback": function(column, aData, iDisplayIndex, iDisplayIndexFull) {
// Bold the grade for all 'A' grade browsers
if (!aData[4])
{
$(column).addClass( 'alert-danger' ).css('background-color', '#f2dede');
}
},
You can get time from timestamp like:
SELECT FROM_UNIXTIME(1447430881);
-> '2015-11-13 10:08:01'
put FROM_UNIXTIME on your timestamp column and get time.
And to get date from datetime use EXTRACT like:
SELECT DATE(datetime) from table;
put both these in your query check the result.

Session id and search script

I have made an search script to search inside various records, but when i add a WHERE session in the sql the script doesn't work anymore. can you please check the code and give me advice how i can change the script so i can get it work?
here are my scripts:
<?php
//include connection file
include_once("connection.php");
session_start();
if (!isset($_SESSION['GEBRUIKER_ID'])) {
header ("Location: ");
die;
}
// initilize all variable
$params = $columns = $totalRecords = $data = array();
$params = $_REQUEST;
//define index of column
$columns = array(
0 =>'id',
1 =>'user_id',
2 => 'klant_id',
3 => 'naam_klant',
4 => 'contactpersoon',
5 => 'adres'
);
$where = $sqlTot = $sqlRec = "";
// check search value exist
if( !empty($params['search']['value'])) {
$where .=" WHERE ";
$where .=" ( naam_klant LIKE '".$params['search']['value']."%' ";
$where .=" OR contactpersoon LIKE '".$params['search']['value']."%' ";
$where .=" OR adres LIKE '".$params['search']['value']."%')";
}
// getting total number records without any search
$sql = "SELECT id,naam_klant,contactpersoon,adres FROM klanten WHERE user_id='".$_SESSION['GEBRUIKER_ID']."' ";
$sqlTot .= $sql;
$sqlRec .= $sql;
//concatenate search sql if value exist
if(isset($where) && $where != '') {
$sqlTot .= $where;
$sqlRec .= $where;
}
$sqlRec .= " ORDER BY ". $columns[$params['order'][0]['column']]." ".$params['order'][0]['dir']." LIMIT ".$params['start']." ,".$params['length']." ";
$queryTot = mysqli_query($conn, $sqlTot) or die("database error:". mysqli_error($conn));
$totalRecords = mysqli_num_rows($queryTot);
$queryRecords = mysqli_query($conn, $sqlRec) or die("error to fetch employees data");
//iterate on results row and create new index array of data
while( $row = mysqli_fetch_row($queryRecords) ) {
$data[] = $row;
}
$json_data = array(
"draw" => intval( $params['draw'] ),
"recordsTotal" => intval( $totalRecords ),
"recordsFiltered" => intval($totalRecords),
"data" => $data // total data array
);
echo json_encode($json_data); // send data as json format
?>
<script type="text/javascript">
$( document ).ready(function() {
$('#employee_grid').DataTable({
"bProcessing": true,
"serverSide": true,
"ajax":{
url :"response.php", // json datasource
type: "post", // type of method ,GET/POST/DELETE
error: function(){
$("#employee_grid_processing").css("display","none");
}
}
});
});
</script>
<div class="container">
<div class="">
<h3>Klanten overzicht</h3>
<div class="">
<table id="employee_grid" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>Klantnummer</th>
<th>Naam</th>
<th>Contactpersoon</th>
<th>Adres</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Klantnummer</th>
<th>Naam</th>
<th>Contactpersoon</th>
<th>Adres</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
When you're constructing your queries, you add a where user_id = ? clause for logged in users apparently. If the search value is not empty, you're adding a second where clause, making the query be essentially select .. from .. where user_id = ? where (naam_klant like ".." OR .. OR ..). You cannot have two wheres in one query, it has to be and, like this:
select .. from .. where user_id = ? AND (naam_klant like ".." OR .. OR ..)

Categories