Display image in server side datatable in php/mysqli and ajax - php

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.

Related

PHP JSON from mysql database not showing any result

I have a problem getting the data in JSON format via the data.php file.
When I try see JSON I got this:
"{"draw":0,"recordsTotal":null,"recordsFiltered":120,"data":[]}"
but needs the php script to retrieve data from the table all entries for the column date, name, id like datatables AJAX instructions . When doing this using the local XAMPP server, the script retrieves the entries from the mysql table and the data is displayed as a table using datatables.
Here is my PHP code
$connect = new PDO("mysql:host=localhost;dbname=abc", "root", "PASSWORD");
$query = "SELECT * FROM abc_result ";
if(isset($_POST["search"]["value"]))
{
$query .= '
WHERE DATE LIKE "%'.$_POST["search"]["value"].'%"
OR NAME LIKE "%'.$_POST["search"]["value"].'%"
OR ID LIKE "%'.$_POST["search"]["value"].'%"
';
}
if(isset($_POST['DATE']))
{
$query .= 'ORDER BY '.$column[$_POST['DATE']['0']['column']].' '.$_POST['DATE']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY ID DESC ';
}
$query1 = '';
if($_POST['length'] != -1)
{
$query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connect->prepare($query);
$statement->execute();
$number_filter_row = $statement->rowCount();
$result = $connect->query($query . $query1);
$data = array();
foreach($result as $row)
{
$sub_array = array();
$sub_array[] = $row['DATE'];
$sub_array[] = $row['NAME'];
$sub_array[] = $row['ID'];
$data[] = $sub_array;
}
function count_all_data($connect)
{
$query = "SELECT COUNT(*) FROM abc_result";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchColumn();
return $result;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => count_all_data($connect),
"recordsFiltered" => $number_filter_row,
"data" => $data
);
echo json_encode($output);
I'm trying to retrieve data from my mysql database and display it using datatables. locally I've been able to do it but I'd like to do it on a NAS (QNAP) so that when I go to a website the table would be visible by anyone who visits it. To do this, I installed MariaDB 5 and PHPmyAdmin. I was able to connect to the database but the php code does not display the data as I would like it to

Querying mySQL database with dropdown values

I've got below snippet where $filter_xx values are extracted from a dropdown basis user choice.
I'm trying to query the mySQL database with what the user chose to query the database with via dropdown selection.
You will see that there are 4 $filter_xx variables and how many of them are set in a given instance is completely random.
The issue is when I use && in the query it checks if all four parameters are true and then throws and output. (Well I know && is suppose to work that way!). I tried replacing all && operators with || and had no luck.
How do I search the database with only options selected by the user?
if(isset($filter_brand) || isset($filter_year) || isset($filter_month) || isset($filter_status))
{
$query = "SELECT * FROM targets WHERE brand='$filter_brand' && startyear='$filter_year' && startmonth='$filter_month' && status='$filter_status' ORDER BY createdon DESC";
} else {
$query = "SELECT * FROM targets ORDER BY createdon DESC";
}
When you have several values that must work in a similar manner, use an array together with loop. I am supposing, you are using mysqli, change quoting for PDO if needed.
$mysqli = new mysqli("localhost", "user", "pass", "test");
//...
//SQL attr name => name of POST parameter
$filter = array('brand' => 'brand', 'startyear' => 'year',
'startmonth' => 'month', 'status' => 'status');
//here we'll store SQL conditions
$sql_filter = array();
foreach($filter as $key => $value)
{
if (isset($_POST[$value]))
{
//use your library function to quote the variable before using it in SQL
$sql_filter[] = $key . '="'. $mysqli->escape_string($_POST[$value]) . '"';
}
}
$query = "SELECT * FROM targets ";
if(isset($sql_filter[0]))
{
$query .= 'WHERE ' . implode(' AND ', $sql_filter) . ' ';
}
$query .= 'ORDER BY createdon DESC';
Try By This
$join = "";
//TAKE ONE BLANK VARIBLE THAT JOIN IF VALUE IS SET
if(isset($filter_brand)){
//IF VALUE ISSET THAN IT ADDED TO QUERY
$join .= " AND brand='$filter_brand'";
}
if(isset($filter_year){
$join .= " AND startyear='$filter_year'";
}
$query = "SELECT * FROM targets WHERE id != '' $join ORDER BY createdon DESC";
You can do something like this:
$query = 'SELECT * FROM targets';
$flag = 0;
if(isset($filter_brand) )
{
$query = "SELECT * FROM targets WHERE brand='$filter_brand'";
$flag = 1;
}
if(isset($filter_year)) {
if($flag==1)
$query .= " &&";
$query .= " startyear='$filter_year'";
$flag = 1;
}
if(isset($filter_month)) {
if($flag==1)
$query .= " &&";
$query = " startmonth='$filter_month'";
$flag = 1;
}
if(isset($filter_status)){
if($flag==1)
$query .= " &&";
$query = " status='$filter_status'";
$flag = 1;
}
if($flag == 1){
$query .= " ORDER BY createdon DESC";
} else {
$query = "SELECT * FROM targets ORDER BY createdon DESC";
}
Try this:
$query = "SELECT * FROM targets WHERE 1 ";
$query = isset($filter_brand) ? $query . " AND brand = '".$filter_brand."'" : $query;
$query = isset($filter_year) ? $query . " AND startyear = '".$filter_year."'" : $query;
$query = isset($filter_month) ? $query . " AND startmonth = '".$filter_month."'" : $query;
$query = isset($filter_status) ? $query . " AND status = '".$filter_status."'" : $query;
$query .= " ORDER BY createdon DESC";

Search function in ajax not working due to failing where statement

I'm doing a table with sort, page and search function.First of all, the code runs well, but after I added where in my sql, the search function doesn't work anymore.
<?php
include_once("connection.php");
session_start();
$db = new dbObj();
$connString = $db->getConnstring();
$params = $_REQUEST;
$action = isset($params['action']) != '' ? $params['action'] : '';
$empCls = new cusinfo($connString);
switch($action)
{
default:
$empCls->getEmployees($params);
return;
}
class cusinfo
{
protected $conn;
protected $data = array();
function __construct($connString)
{
$this->conn = $connString;
}
public function getEmployees($params)
{
$this->data = $this->getRecords($params);
echo json_encode($this->data);
}
function getRecords($params) {
$rp = isset($params['rowCount']) ? $params['rowCount'] : 10;
if (isset($params['current'])) { $page = $params['current']; } else { $page=1; };
$start_from = ($page-1) * $rp;
$sql = $sqlRec = $sqlTot = $where = '';
if( !empty($params['searchPhrase']) )
{
$where .=" WHERE ";
$where .=" ( NO_ID LIKE '".$params['searchPhrase']."%' ";
$where .=" OR TICKET_ID LIKE '".$params['searchPhrase']."%' ";
$where .=" OR CAT_C_B LIKE '".$params['searchPhrase']."%' ";
$where .=" OR ORDER_TYPE LIKE '".$params['searchPhrase']."%' ";
$where .=" OR AGENT_STAFF_NAME LIKE '".$params['searchPhrase']."%' ";
$where .=" OR EFORM_ID LIKE '".$params['searchPhrase']."%' ";
$where .=" OR LATEST_ORDER_STATUS LIKE '".$params['searchPhrase']."%' )";
}
if( !empty($params['sort']) )
{
$where .=" ORDER By ".key($params['sort']) .' '.current($params['sort'])." ";
}
// getting total number records without any search
$role = $_SESSION['sess_userrole'];
$uid = $_SESSION['sess_user_id'];
$tid = $_SESSION['tmid'];
$mid = $_SESSION['mid'];
$sid = $_SESSION['sid'];
if($role=="admin")
{
$sql = "SELECT * FROM `cusinfo` where AGENT_CODE_STAFF_ID IN (SELECT id FROM `users` where tm_groupid = '$tid') ";
$sqlTot .= $sql;
$sqlRec .= $sql;
}
else
{
.
.
.
}
//concatenate search sql if value exist
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 customer data");
$queryRecords = mysqli_query($this->conn, $sqlRec) or die("error to fetch customer data");
while( $row = mysqli_fetch_assoc($queryRecords) )
{
$data[] = $row;
}
$json_data = array(
"current" => $page,
"rowCount" => 10,
"total" => intval($qtot->num_rows),
"rows" => $data // total data array
);
return $json_data;
}
}
?>
Thankyou for all of the reply,this question have been solve by myself.It can be solve by just change the where to AND on the code bellow:
if( !empty($params['searchPhrase']) )
{
$where .=" WHERE";//change this line to $where .=" AND";
.
.
.
}

how to change row font color or background color base on values in PHP json im using bootgrid

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;
}
...

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