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
Related
I have 4 tables as below: account_catagory, chartofaccount, general_leadger, and account_money.
Every accounts in chartofaccount has relationship with account_catagory.
Every leadger has relationship with chartofaccount.
every account_money has relationship with general_leadger.
now I want to select my all account_catagories and join it with chartofaccount, join it with general leadger, and join it with account_money which gives me lots of record.
I want to show them in expandable table so every child come under its own parent.
I wrote some code but didn't get the result as expected.
<table class="table table-condensed table-striped mt-1 p-0">
<tbody class="p-0">
<?php
$counter = 0;
$conn = new Connection();
$query = "SELECT * FROM account_catagory
LEFT JOIN chartofaccount ON account_catagory.account_catagory_id = chartofaccount.account_catagory
WHERE account_catagory.catagory = ? AND account_catagory.company_id = ?";
$result = $conn->Query($query, ["Revenue", $user_data->company_id]);
$results = $result->fetchAll(PDO::FETCH_OBJ);
foreach ($results as $item) {
$q = "SELECT * FROM general_leadger
LEFT JOIN account_money ON general_leadger.leadger_id = account_money.leadger_ID
WHERE general_leadger.recievable_id = ? OR general_leadger.payable_id = ?";
$r = $conn->Query($q, [$item->chartofaccount_id, $item->chartofaccount_id]);
$RES = $r->fetchAll(PDO::FETCH_OBJ);
$total = 0;
foreach ($RES as $LID) {
if ($item->chartofaccount_id == $LID->account_id) {
if ($LID->currency_rate != 0) {
$total += ($LID->amount * $LID->currency_rate);
} else {
$total += $LID->amount;
}
}
}
echo "<tr data-toggle='collapse' data-target='#row$counter' class='accordion-toggle p-0'>
<td>
<button class='btn btn-blue btn-xs p-0'><span class='las la-plus'></span></button>
<span>$item->account_name</span>
</td>
<td class='text-right'>$total</td>
</tr>";
$total = 0;
$counter++;
if (checkChilds($item->account_catagory_id) > 0) {
recurSearch2($user_data->company_id, $item->account_catagory_id);
}
}
?>
</tbody>
</table>
I have a function that checks if the parent has a child which is below:
function checkChilds($patne)
{
$conn = new Connection();
$query = "SELECT * FROM account_catagory WHERE parentID = ?";
$result = $conn->Query($query, [$patne]);
$results = $result->rowCount();
return $results;
}
and another function that selects all the children using the recursive function:
function recurSearch2($c, $parentID)
{
$counter = 0;
$conn = new Connection();
$query = "SELECT * FROM account_catagory
INNER JOIN chartofaccount ON account_catagory.account_catagory_id = chartofaccount.account_catagory
WHERE account_catagory.parentID = ? AND account_catagory.company_id = ?";
$result = $conn->Query($query, [$parentID, $c]);
$results = $result->fetchAll(PDO::FETCH_OBJ);
foreach ($results as $item) {
$q = "SELECT * FROM general_leadger
LEFT JOIN account_money ON general_leadger.leadger_id = account_money.leadger_ID
WHERE general_leadger.recievable_id = ? OR general_leadger.payable_id = ?";
$r = $conn->Query($q, [$item->chartofaccount_id, $item->chartofaccount_id]);
$RES = $r->fetchAll(PDO::FETCH_OBJ);
$total = 0;
foreach ($RES as $LID) {
if ($item->chartofaccount_id == $LID->account_id) {
if ($LID->currency_rate != 0) {
$total += ($LID->amount * $LID->currency_rate);
} else {
$total += $LID->amount;
}
}
}
echo "<tr class='p-0'>
<td colspan='3' class='hiddenRow'>
<div class='accordian-body collapse' id='row$counter'>
<table class='table table-striped'>
<tbody>
<tr data-toggle='collapse' class='accordion-toggle' data-target='#row$counter'>
<td>
<button class='btn btn-blue btn-xs p-0'><span class='las la-plus'></span></button>
<span>$item->account_name</span>
</td>
<td>$total</td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>";
$total = 0;
$counter++;
if (checkChilds($item->account_catagory_id) > 0) {
recurSearch2($c, $item->account_catagory_id);
}
}
}
the result I get using code is below:
the result I want is as below:
I want to add this line
a href="r.php?id=<?php echo $row['id']; ?>" >Details>
which will display details of this id on another page.
but i don't know how to write this line correctly. can you help me please thank you.
$conn = new mysqli('localhost', 'root', '', 'dbmtc');
$perPage = 10;
$page = 0;
if (isset($_POST['page'])) {
$page = $_POST['page'];
} else {
$page=1;
};
$startFrom = ($page-1) * $perPage;
$sqlQuery = "SELECT fname, lname, dept, email
FROM staff ORDER BY fname ASC LIMIT $startFrom, $perPage";
//echo $sqlQuery;
$result = mysqli_query($conn, $sqlQuery);
$paginationHtml = '';
while ($row = mysqli_fetch_assoc($result)) {
$paginationHtml.='<tr>';
$paginationHtml.='<td>'.$row["fname"].' '.$row["lname"].'</td>';
$paginationHtml.='<td>'.$row["dept"].'</td>';
$paginationHtml.='<td>'.$row["email"].'</td>';
**this line should be here**
$paginationHtml.='</tr>';
}
$jsonData = array(
"html" => $paginationHtml,
);
echo json_encode($jsonData);
?>
This part is in index.php
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Department</th>
<th>Email</th>
<th>Operations</th>
</tr>
</thead>
<tbody id="content">
</tbody>
</table>
This is the table
And when i insert
$paginationHtml .= '<td>Details</td>';
I got this I don't why, that why I said it's not good
enter image description here
First of all: You didn't select the ID in your sql query. Please add it in the selected fieds.
These are the possibilities to write this and you can choose one of them:
1- $paginationHtml .= '<td><a href="r.php?id='.$row['id'].'" >Details</a></td>';
2- $paginationHtml .= "<td><a href=\"r.php?id={$row['id']}\" >Details</a></td>";
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>
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.
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 ..)