Search function in ajax not working due to failing where statement - php

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

Related

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

search by multiple field. sometimes by one field and sometimes more than one field

I have search form. in here multiple field. sometimes I will form submit with one field, sometimes form submit with two and sometimes multiple field value.
if (isset($_POST['search'])) {
$projectName = $_POST['pName'];
$clientId = $_POST['s_by_clientName'];
$departmentId = $_POST['s_by_department'];
$statusName = $_POST['s_by_status'];
if (!empty($projectName))
{
$searchSql = mysql_query("select * from project_list where projectName='$projectName'");
}
if (!empty($clientId))
{
$searchSql = mysql_query("select * from project_list where client_id='$clientId'");
}
if (!empty($departmentId))
{
$searchSql = mysql_query("select * from project_list where department_id='$departmentId'");
}
if (!empty($statusName))
{
$searchSql = mysql_query("select * from project_list where status='$statusName'");
}
}
these query only for search by single field.
how to make query that performs searching by one or multiple field value
is it possible??
Use Concatenation in query Variable
$searchSql ="select * from project_list where 1=1 ";
if (isset($_POST['search'])) {
$projectName = $_POST['pName'];
$clientId = $_POST['s_by_clientName'];
$departmentId = $_POST['s_by_department'];
$statusName = $_POST['s_by_status'];
if (!empty($projectName))
{
$searchSql. = " AND projectName='$projectName'";
}
if (!empty($clientId))
{
$searchSql. = " AND client_id='$clientId'";
}
if (!empty($departmentId))
{
$searchSql. = " AND department_id='$departmentId'";
}
if (!empty($statusName))
{
$searchSql. = " AND status='$statusName'";
}
}
$result=mysql_query($searchSql);
NOTE:mysql_query() has been deprecated in PHP 5.5 and removed in PHP 7. Kindly update to use mysqli library of PDO.
You can build an increntale query
<code>
if (isset($_POST['search'])) {
$projectName = $_POST['pName'];
$clientId = $_POST['s_by_clientName'];
$departmentId = $_POST['s_by_department'];
$statusName = $_POST['s_by_status'];
$my_sql = "select * from project_list ";
$my_where = "";
if (!empty($projectName))
{
if ($my_where = ""){
$my_sql .= "where ";
} else {
$my_sql .= "and ";
}
$my_sql .= "projectName='$projectName'";
}
if (!empty($clientId))
{
if ($my_where = ""){
$my_sql .= "where ";
} else {
$my_sql .= "and ";
}
$my_sql .= "client_id='$clientId'";
}
if (!empty($departmentId))
{
if ($my_where = ""){
$my_sql .= "where ";
} else {
$my_sql .= "and ";
}
$my_sql .= "department_id='$departmentId'";
}
if (!empty($statusName))
{
if ($my_where = ""){
$my_sql .= "where ";
} else {
$my_sql .= "and ";
}
$my_sql .= "status='$statusName'";
}
}
Here I used column id as primary key & auto-increment. Change it as per your column name.
$query = "SELECT * FROM project_list WHERE id is not null";
Code
<?
if (isset($_POST['search'])) {
$projectName = $_POST['pName'];
$clientId = $_POST['s_by_clientName'];
$departmentId = $_POST['s_by_department'];
$statusName = $_POST['s_by_status'];
// Here I used coloumn 'id' as primary key & auto-increment. Change it as per your column name.
$query = "SELECT * FROM project_list WHERE id is not null"
if (!empty($projectName))
{
$query. = " AND projectName='".$projectName."'";
}
if (!empty($clientId))
{
$query. = " AND client_id='".$clientId."'";
}
if (!empty($departmentId))
{
$query. = " AND department_id='".$departmentId."'";
}
if (!empty($statusName))
{
$query. = " AND project_list='".$statusName."'";
}
$searchSql = mysql_query($query);
}

two methods in a class so close in what they do

I have this class that has these two methods that are so closely related to the each other. I do not want to pass the flags so I kept them separate. I was wondering if there is a way to rewrite it so that I do not have to repeat so closely!
class Test extends Controller
{
public static function nonFormattedData($param)
{
$arr = array();
if (is_array($param)) {
$i = 0;
$sql = "
select *
from table1
where
";
if (isset($param['startDate'])) {
$sql .= " date_created between ? AND ?";
$arr[] = $param['startDate'];
$arr[] = $param['endDate'];
$i++;
}
if (isset($param['amount']) && !empty($param['amount'])) {
if ($i > 0) $sql .= " AND ";
$sql .= " balance= ?";
$arr[] = $param['amount'];
$i++;
}
if (isset($param) && !empty($param['amount'])) {
if ($i > 0) $sql .= " AND ";
$sql .= " balance= ?";
$arr[] = $param['amount'];
$i++;
}
if (isset($param['createdBy']) && !empty($param['createdBy'])) {
if ($i > 0) $sql .= " AND ";
$sql .= " column2 like '%Created By: " . $param['createdBy'] . "%'";
}
$sql .= ' group by id.table1 ';
$rs = Query::RunQuery($sql, $arr);
foreach ($rs as $row) {
$records = new Account();
$results[] = $records;
}
return $results;
}
}
public static function formattedData($serArray, $orderBy = "giftcardaccount_id desc", $offset = 0, $limit = 10)
{
$arr = array();
if (is_array($param)) {
$i = 0;
$sql = "
select *
from table1
where
";
if (isset($param['startDate'])) {
$sql .= " date_created between ? AND ?";
$arr[] = $param['startDate'];
$arr[] = $param['endDate'];
$i++;
}
if (isset($param['amount']) && !empty($param['amount'])) {
if ($i > 0) $sql .= " AND ";
$sql .= " balance= ?";
$arr[] = $param['amount'];
$i++;
}
if (isset($param) && !empty($param['amount'])) {
if ($i > 0) $sql .= " AND ";
$sql .= " balance= ?";
$arr[] = $param['amount'];
$i++;
}
if (isset($param['createdBy']) && !empty($param['createdBy'])) {
if ($i > 0) $sql .= " AND ";
$sql .= " column2 like '%Created By: " . $param['createdBy'] . "%'";
}
$sql .= ' group by id.table1 ';
$rs = Query::RunQuery($sql, $arr);
return array("data" => $rs);
}
}
}
Why not have one method, but with an optional formatting options object/array?
public static function getData($params, $formatting = null) {
// continue as normal, adding formatting if it's there
}

Give back more than one mysql result in an php class

I'm trying to build my own CMS in classes.
Now I have got a problem when I try to get data from my MySQL database
Instead of one item i'd like to get an collection of all my items
At the end I'd like to get an Object so I can read it out like : $item->id
Here's my code :
static function getContentItems($id, $active, $sort_by, $sort_type, $limit) {
if (isset($id) && !empty($id)) {
$where .= "WHERE id = ".$id;
}
if (isset($active) && !empty($active)) {
$where .= " AND active = ".$active;
}
if (isset($sort_by) && !empty($sort_by)) {
$where .= " ORDER BY ".$sort_by;
if (isset($sort_type) && !empty($sort_type)) {
$where .= " ".$sort_type;
}
}
if (isset($limit) && !empty($limit)) {
$where .= " LIMIT 0,".$limit;
}
if (isset($where) && !empty($where)) {
$query = "SELECT * FROM content ".$where;
} else {
$query = "SELECT * FROM content";
}
$result = mysql_query($query)or die(mysql_error());
$item = new ContentItem();
while ($data = mysql_fetch_array($result)) {
$item->id = $data['id'];
}
return $item;
}
}
dont start your $where string with .
if (isset($id) && !empty($id)) {
$where = "WHERE id = ".$id;
}
and alwez print your $query
Better Solution
if (!empty($id) {
$where = " WHERE id = ".$id;
if (!empty($active)) {
$where .= " AND active = ".$active;
if (!empty($sort_by)) {
$where .= " ORDER BY ".$sort_by;
if (!empty($sort_type)) {
$where .= " ".$sort_type;
}
}
}
}
if (empty($limit)) {
$where .= " LIMIT 0,".$limit;
}
and later
$item = new ContentItem();
$data = array(); $i=0;
while ($data = mysql_fetch_object($result)) {
$search_result[$i] = $data;
$i++;
}
return $search_result;
and any id can be retrieve by $search_result[$i]->id
Why don't you use Arrays?
Like this:
$collection = array();
while ($data = mysql_fetch_array($result)) {
$item = new ContentItem();
$item->id = $data['id'];
$collection[] = $item; //Appends the item to the array
}
return $collection;
You can access your array in this way:
$collection = YourClassName::getContentItems(...);
foreach($collection as $item) {
// do something with each $item
print_r($item);
}
Look into using mysql_fetch_object http://php.net/manual/en/function.mysql-fetch-object.php instead of mysql_fetch_array.. it returns rows the db as an object already

SQL Multiple WHERE Clause Problem

I'm attempting the modify this Modx Snippet so that it will accept multiple values being returned from the db instead of the default one.
tvTags, by default, was only meant to be set to one variable. I modified it a bit so that it's exploded into a list of variables. I'd like to query the database for each of these variables and return the tags associated with each. However, I'm having difficulty as I'm fairly new to SQL and PHP.
I plugged in $region and it works, but I'm not really sure how to add in more WHERE clauses for the $countries variable.
Thanks for your help!
if (!function_exists('getTags')) {
function getTags($cIDs, $tvTags, $days) {
global $modx, $parent;
$docTags = array ();
$baspath= $modx->config["base_path"] . "manager/includes";
include_once $baspath . "/tmplvars.format.inc.php";
include_once $baspath . "/tmplvars.commands.inc.php";
if ($days > 0) {
$pub_date = mktime() - $days*24*60*60;
} else {
$pub_date = 0;
}
list($region, $countries) = explode(",", $tvTags);
$tb1 = $modx->getFullTableName("site_tmplvar_contentvalues");
$tb2 = $modx->getFullTableName("site_tmplvars");
$tb_content = $modx->getFullTableName("site_content");
$query = "SELECT stv.name,stc.tmplvarid,stc.contentid,stv.type,stv.display,stv.display_params,stc.value";
$query .= " FROM ".$tb1." stc LEFT JOIN ".$tb2." stv ON stv.id=stc.tmplvarid ";
$query .= " LEFT JOIN $tb_content tb_content ON stc.contentid=tb_content.id ";
$query .= " WHERE stv.name='".$region."' AND stc.contentid IN (".implode($cIDs,",").") ";
$query .= " AND tb_content.pub_date >= '$pub_date' ";
$query .= " AND tb_content.published = 1 ";
$query .= " ORDER BY stc.contentid ASC;";
$rs = $modx->db->query($query);
$tot = $modx->db->getRecordCount($rs);
$resourceArray = array();
for($i=0;$i<$tot;$i++) {
$row = #$modx->fetchRow($rs);
$docTags[$row['contentid']]['tags'] = getTVDisplayFormat($row['name'], $row['value'], $row['display'], $row['display_params'], $row['type'],$row['contentid']);
}
if ($tot != count($cIDs)) {
$query = "SELECT name,type,display,display_params,default_text";
$query .= " FROM $tb2";
$query .= " WHERE name='".$region."' LIMIT 1";
$rs = $modx->db->query($query);
$row = #$modx->fetchRow($rs);
$defaultOutput = getTVDisplayFormat($row['name'], $row['default_text'], $row['display'], $row['display_params'], $row['type'],$row['contentid']);
foreach ($cIDs as $id) {
if (!isset($docTags[$id]['tags'])) {
$docTags[$id]['tags'] = $defaultOutput;
}
}
}
return $docTags;
}
}
You don't add in more WHERE clauses, you use ANDs and ORs in the already existing where clause. I would say after the line $query .= " WHERE stv.name = '".$region... you put in
foreach ($countries as $country)
{
$query .= "OR stv.name = '{$country}', ";
}
but I don't know how you want the query to work.

Categories