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 ..)
Related
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 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;
}
THIS IS MY PHP CODE how can i changed the font color of specific row based on the value
$sql = "SELECT * FROM employee "; $sqlTot .= $sql; $sqlRec .= $sql;
if(isset($where) && $where != '') {
$sqlTot .= $where;
$sqlRec .= $where;
}
if ($rp!=-1)
$sqlRec .= " LIMIT ". $start_from .",".$rp;
$qtot = mysqli_query($this->conn, $sqlTot) or die("error to fetch tot seaman's data");
$queryRecords = mysqli_query($this->conn, $sqlRec) or die("error to fetch seaman's data");
while( $row = mysqli_fetch_assoc($queryRecords) ) {
$data[] = $row;
}
$json_data = array(
"current" => intval($params['current']),
"rowCount" => 10,
"total" => intval($qtot->num_rows),
"rows" => $data // total data array
);
return $json_data;
}
Add more details about your client-side code. according to comments, you can change your code to this one:
...
while( $row = mysqli_fetch_assoc($queryRecords) ) {
if ($you_want)
$row['remarks'] = 'ACTIVE';
$data[] = $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.
I am trying with server side script datatable where I need to add images inside the table. The image path is stored inside the database. I need to display the images in my page. How can I add images in the page. Here is the code.I want the images to be displayed using mysqli and ajax.
<?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 =>'name',
2=>'images',
3 => 'year',
4 => 'rank'
);
$where = $sqlTot = $sqlRec = "";
// check search value exist
if( !empty($params['search']['value']) ) {
$where .=" WHERE ";
$where .=" (name LIKE '".$params['search']['value']."%' ";
$where .=" OR year LIKE '".$params['search']['value']."%' ";
$where .=" OR id LIKE '".$params['search']['value']."%' ";
$where .=" OR rank LIKE '".$params['search']['value']."%' )";
}
// getting total number records without any search
$sql = "SELECT * FROM `search` ";
$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 rank holders");
//iterate on results row and create new index array of data
while( $row = mysqli_fetch_row($queryRecords) ) {
$data[] = $row;
$data[] = "<img src =images/".$data[2].">";
$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
?>
Because you store the pic in the DB, you can send in ajax the base64 encoding of the pic you want to display.