Search within many table php with wildcard - php

please help me, i want to make search query but list of table is not shown in php but it work in mysql..here is my code
//$sql = "SELECT * FROM table_name WHERE 1=1" work perfectly
$sql = "SELECT a.* FROM (SELECT table_name FROM information_schema.tables WHERE table_schema like 'rft%') a where 1=1";
if( !empty($requestData['search']['value']) )
{ // if there is a search parameter, $requestData['search']['value'] contains search parameter
//search based on input
$sql.=" AND ( Code LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR Year LIKE '".$requestData['search']['value']."%' )";
}
//start search after input
$query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees");
$totalFiltered = mysqli_num_rows($query);
continue here
// when there is a search parameter then we have to modify total number filtered rows as per search result.
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." ";
/* $requestData['order'][0]['column'] contains colmun index, $requestData['order'][0]['dir'] contains order such as asc/desc */
$query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees");
$data = array();
while( $row=mysqli_fetch_array($query) )
{ // preparing an array
$nestedData=array();
$nestedData[] = $row["Type"];
$nestedData[] = $row["Code"];
$nestedData[] = $row["Year"];
$data[] = $nestedData;
}

You only select table_name from information_schema.tables and later you do your WHERE code=.... There is no Code in the result of your select, so this can't work.
If I get correctly what you are trying to do you have to do it in two steps like this:
// get all table names:
$tquery = mysqli_query($conn, "SELECT table_name FROM information_schema.tables WHERE table_schema like 'rft%'");
while ($table = mysqli_fetch_array($tquery)) {
// do your query per table
$sql = "SELECT * FROM " . $table['table_name'] . " WHERE ( Code LIKE '".$requestData['search']['value']."%' ";
$sql .=" OR Year LIKE '".$requestData['search']['value']."%' )";
$query = mysqli_query($conn, $sql);
while ( $row = mysqli_fetch_array($query) ) {
// do what you want with $row
}
}

Related

Serverside datatable search show extra data

Hi I'm working on processing data in datatable using serverside processing. I've managed to show the data in the table but I haven't fully understood how it works with searches, I've included some code in the php file, but when I search for something with a where clause in the query it does show other values as well, this is my code for request.php
// storing request (ie, get/post) global array to a variable
$requestData = filter_var_array($_REQUEST);
$columns = array(
// datatable column index => database column name
0 => 'user_first',
1 => 'user_last',
2 => 'user_email',
);
// getting total number records without any search
$sql = "SELECT user_id, user_first, user_last, user_email, user_role";
$sql .=" FROM users WHERE user_role='partner'";
$query= mysqli_query($conn, $sql);
$totalData = mysqli_num_rows($query);
$totalFiltered = $totalData; // when there is no search parameter then total number rows = total number filtered rows.
if( !empty($requestData['search']['value']) ) {
// if there is a search parameter
$sql = "SELECT user_first, user_last, user_email";
$sql.=" FROM users WHERE user_role='partner'";
$sql.=" AND user_first LIKE '".$requestData['search']['value']."%' "; // $requestData['search']['value'] contains search parameter
$sql.=" OR user_last LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR user_email LIKE '".$requestData['search']['value']."%' ";
$query=mysqli_query($conn, $sql);
$totalFiltered = mysqli_num_rows($query); // when there is a search parameter then we have to modify total number filtered rows as per search result without limit in the query
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." "; // $requestData['order'][0]['column'] contains colmun index, $requestData['order'][0]['dir'] contains order such as asc/desc , $requestData['start'] contains start row number ,$requestData['length'] contains limit length.
$query=mysqli_query($conn, $sql); // again run query with limit
} else {
$sql = "SELECT user_first, user_last, user_email";
$sql.=" FROM users WHERE user_role='partner'";
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." ";
$query=mysqli_query($conn, $sql);
}
$data = array();
while( $row=mysqli_fetch_array($query) ) { // preparing an array
// Query al database per ottenere i gruppi a cui appartengono i condomini
$query_group_id = mysqli_prepare($conn, "SELECT group_name, group_id FROM user_group_join LEFT OUTER JOIN user_group ON user_group_join . group_join_id = user_group . group_id WHERE user_join_id = ?");
mysqli_stmt_bind_param($query_group_id, 'i', $row["user_id"]);
mysqli_stmt_execute($query_group_id);
mysqli_stmt_store_result($query_group_id);
mysqli_stmt_bind_result($query_group_id, $group_names, $group_ids);
$response=array();
while (mysqli_stmt_fetch($query_group_id)){
$response[]=$group_names;
}
$nestedData=array();
$nestedData[] = '<b><a onclick="ViewPartnerDetail('.$row["user_id"].')">'.ucfirst($row["user_first"]).' '.ucfirst($row["user_last"]).'</a></b>';
$nestedData[] = $row["user_email"];
$nestedData[] = '<select class="bs-select form-control show-menu-arrow"><option>'.implode("<option>",$response).'</option></select>';
$nestedData[] = '<button onclick="GetPartnerDetail('.$row["user_id"].')" class="btn btn-sm blue center"> <i class="fa fa-pencil-square-o"></i></button>';
$nestedData[] = '<button onclick="DeletePartner('.$row["user_id"].')" class="btn btn-sm red"> <i class="fa fa-trash-o"></i></button>';
$data[] = $nestedData;
}
$json_data = array(
"draw" => intval( $requestData['draw'] ), // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw.
"recordsTotal" => intval( $totalData ), // total number of records
"recordsFiltered" => intval( $totalFiltered ), // total number of records after searching, if there is no searching then totalFiltered = totalData
"data" => $data // total data array
);
echo json_encode($json_data); // send data as json format

Why it seems that the WHERE clause in my query doesn't work?

This code I'm using works fine but when I tried to query with a where clause, it looks like it doesn't work, it still displays all the data though I put a condition already. I also tried changing the way I put the where clause, but it says "no data found in the server" so I put the code back to its original form. I also tried putting a specific where clause like "where client = 'eadept'" but it still shows all details. This is my code.
session_start();
/* Database connection start */
$servername = "localhost";
$item = "root";
$password = "";
$dbname = "sample";
$conn = mysqli_connect($servername, $item, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
/* Database connection end */
// storing request (ie, get/post) global array to a variable
$requestData = $_REQUEST;
$columns = array(
// datatable column index => database column name
0 => 'facility',
1 => 'title',
2 => 'start',
3 => 'end',
4 => 'fee',
5 => 'status'
);
$uname = ($_SESSION['username']);
// getting total number records without any search
$sql = "SELECT facility, title, start, end, fee, status ";
$sql .= " FROM reservation WHERE client = '$uname'";
$query = mysqli_query($conn, $sql);
$totalData = mysqli_num_rows($query);
$totalFiltered = $totalData; // when there is no search parameter then total number rows = total number filtered rows.
$sql = "SELECT facility, title, start, end, fee, status ";
$sql .= " FROM reservation WHERE 1=1";
if(!empty($requestData['search']['value'])) { // if there is a search parameter, $requestData['search']['value'] contains search parameter
$sql .= " AND ( facility LIKE '" . $requestData['search']['value'] . "%' ";
$sql .= " OR title LIKE '" . $requestData['search']['value'] . "%' ";
$sql .= " OR fee LIKE '" . $requestData['search']['value'] . "%' )";
}
$query = mysqli_query($conn, $sql);
$totalFiltered = mysqli_num_rows($query); // when there is a search parameter then we have to modify total number filtered rows as per search result.
$sql .= " ORDER BY " . $columns[$requestData['order'][0]['column']] . " " . $requestData['order'][0]['dir'] . " LIMIT " . $requestData['start'] . " ," . $requestData['length'] . " ";
// $sql.="WHERE client = 'eadept'";
/* $requestData['order'][0]['column'] contains colmun index, $requestData['order'][0]['dir'] contains order such as asc/desc */
$query = mysqli_query($conn, $sql);
$data = array();
while($row = mysqli_fetch_array($query)) { // preparing an array
$nestedData = array();
$nestedData[] = $row["facility"];
$nestedData[] = $row["title"];
$nestedData[] = $row["start"];
$nestedData[] = $row["end"];
$nestedData[] = $row["fee"];
$nestedData[] = $row["status"];
$data[] = $nestedData;
}
$json_data = array(
"draw" => intval($requestData['draw']), // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw.
"recordsTotal" => intval($totalData), // total number of records
"recordsFiltered" => intval($totalFiltered), // total number of records after searching, if there is no searching then totalFiltered = totalData
"data" => $data // total data array
);
echo json_encode($json_data); // send data as json format
I'm referring to the query under the array. Can anyone please help and tell what to change so it will work?
I noticed that I'm just putting the query on a wrong place. This is the right code to do the WHERE clause.
$uname = ($_SESSION['username']);
// getting total number records without any search
$sql = "SELECT facility, item, start, end, fee, status ";
$sql.=" FROM reservation";
$query=mysqli_query($conn, $sql);
$totalData = mysqli_num_rows($query);
$totalFiltered = $totalData; // when there is no search parameter then total number rows = total number filtered rows.
$sql = "SELECT facility, item, start, end, fee, status ";
$sql.=" FROM reservation WHERE client = '$uname'";
if( !empty($requestData['search']['value']) ) { // if there is a search parameter, $requestData['search']['value'] contains search parameter
$sql.=" AND ( facility LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR item LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR fee LIKE '".$requestData['search']['value']."%' )";
// $sql.=" OR item LIKE '".$requestData['search']['value']."%' )";
// $sql.=" OR start LIKE '".$requestData['search']['value']."%' )";
// $sql.=" OR end LIKE '".$requestData['search']['value']."%' )";
// $sql.=" OR fee LIKE '".$requestData['search']['value']."%' )";
// $sql.=" OR status LIKE '".$requestData['search']['value']."%' )";
}
$query=mysqli_query($conn, $sql);
$totalFiltered = mysqli_num_rows($query); // when there is a search parameter then we have to modify total number filtered rows as per search result.
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." ";
// $sql.="WHERE client = 'eadept'";
/* $requestData['order'][0]['column'] contains colmun index, $requestData['order'][0]['dir'] contains order such as asc/desc */
$query=mysqli_query($conn, $sql);

How can i order by id ascending?

I want to order data by Id, how can i do this ?
if($_GET["grupid"]>0){
$DUZEN = array();
$sql = "SELECT * FROM siparis_ana WHERE grupid =".$_GET["grupid"];
$rsDuzen = mysql_query($sql, $conn) or die(mysql_error());
while ($r = mysql_fetch_assoc($rsDuzen)) {
$DUZEN[] = $r;
}
}
i can read all data with this code which have same group id. But data aline random.
You have to use mysql order clause in your query like order by id asc. Which you can use at the end of your query.
$sql = "SELECT * FROM siparis_ana WHERE grupid =".$_GET["grupid"]." order by id asc";
Your sql query should be like given below...
$sql = "SELECT * FROM siparis_ana where grupid = " . $_GET['grupid'] . " ORDER BY id asc ";

datatables + lengthMenu + All + serverside processing + handling -1/All

this is a basic datatables fiddle
this is a basic datatables fiddle with lengthMenu
What I want to do is get this working in my serverside processing example.
I can get the dropdown to appear right doing the following to my index.php file.
$(document).ready(function() {
var dataTable = $('#employee-grid').DataTable({
"lengthMenu": [
[10, 25, 50, -1],
[10, 25, 50, "All"]
],
"processing": true,
"serverSide": true,
"ajax": {
url: "employee-grid-data.php", // json datasource
type: "post", // method , by default get
error: function() { // error handling
$(".employee-grid-error").html("");
$("#employee-grid").append('<tbody class="employee-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
$("#employee-grid_processing").css("display", "none");
}
}
});
});
So that works okay if I select 10, 25 or 50 but if I select All I get No data found in the server.
So my issue is in my employee-grid-data.php file,noted here, and this is where I am having my difficulty. I need to do an if statement to handle this All option or -1 as this is what I pass to the server when I select All in $requestData['length']
I have identified the 2 areas where I use $requestData['length'] and this I belive to be the issue.
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." "; // $requestData['order'][0]['column'] contains colmun index, $requestData['order'][0]['dir'] contains order such as asc/desc , $requestData['start'] contains start row number ,$requestData['length'] contains limit length.
$query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees"); // again run query with limit
So what I have to do is try and write such that:
if $requestData['length'] NOT equals -1
do this line
else
do this line without using $requestData['length'] as a parameter.
This is where I am having difficulty.
This is my attempt, but this could be a syntax issue or something else. I'm not very good at debugging this.
if ($requestData['length']!==-1){
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." ";
} else {
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']
}
$query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees");
When I visit the page index.php I get No data found in the server and in the console I get 500 (Internal Server Error).
Can anyone advise what my code should look like?
Or how could I debug this?
I would ideally like to be able to add a basic if else statement just to see if I could get that bit right alone, but not sure how to do this in this setup. with Javasecript I would normally use console.log
Here is my entire employee-grid-data.php file for reference:
<?php
/* Database connection start */
$servername = "localhost";
$username = "root";
$password = "Password1";
$dbname = "test";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
/* Database connection end */
// storing request (ie, get/post) global array to a variable
$requestData= $_REQUEST;
$columns = array(
// datatable column index => database column name
0 =>'employee_name',
1 => 'employee_salary',
2=> 'employee_age'
);
// getting total number records without any search
$sql = "SELECT employee_name, employee_salary, employee_age ";
$sql.=" FROM employee";
$query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees");
$totalData = mysqli_num_rows($query);
$totalFiltered = $totalData; // when there is no search parameter then total number rows = total number filtered rows.
if( !empty($requestData['search']['value']) ) {
// if there is a search parameter
$sql = "SELECT employee_name, employee_salary, employee_age ";
$sql.=" FROM employee";
$sql.=" WHERE employee_name LIKE '".$requestData['search']['value']."%' "; // $requestData['search']['value'] contains search parameter
$sql.=" OR employee_salary LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR employee_age LIKE '".$requestData['search']['value']."%' ";
$query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees");
$totalFiltered = mysqli_num_rows($query); // when there is a search parameter then we have to modify total number filtered rows as per search result without limit in the query
if ($requestData['length']!==-1){
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." "; // $requestData['order'][0]['column'] contains colmun index, $requestData['order'][0]['dir'] contains order such as asc/desc , $requestData['start'] contains start row number ,$requestData['length'] contains limit length.
} else {
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']
}
$query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees"); // again run query with limit
} else {
$sql = "SELECT employee_name, employee_salary, employee_age ";
$sql.=" FROM employee";
if ($requestData['length']!==-1){
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." ";
} else {
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']
}
$query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees");
}
$data = array();
while( $row=mysqli_fetch_array($query) ) { // preparing an array
$nestedData=array();
$nestedData[] = $row["employee_name"];
$nestedData[] = $row["employee_salary"];
$nestedData[] = $row["employee_age"];
$data[] = $nestedData;
}
$json_data = array(
"draw" => intval( $requestData['draw'] ), // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw.
"recordsTotal" => intval( $totalData ), // total number of records
"recordsFiltered" => intval( $totalFiltered ), // total number of records after searching, if there is no searching then totalFiltered = totalData
"data" => $data // total data array
);
echo json_encode($json_data); // send data as json format
?>
edit1 good link for testing http://phpfiddle.org/
This is the code I had to add to handle the $requestData['length'] equaling -1. I had to add wherever I had $requestData['length']. This is the best I could do.
if ($requestData['length'] > 0 ){
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." ";
} else {
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." ";
}

mysqli multiple query

I do following:
$query .=" SELECT * , COUNT(PRESENT) FROM seventh_a";
$query .=" WHERE class ='0' AND NAME ='Alexander Kirkby Scherer'";
$query .=" AND PRESENT = 'TS' GROUP BY lesson";
$query = " SELECT * , COUNT(lesson) FROM seventh_a";
$query .=" WHERE class ='0' AND NAME ='Alexander Kirkby Scherer'";
$query .=" GROUP BY lesson";
After that I can echo out $row['COUNT(PRESENT)'] but not $row['COUNT(lesson)'].
Can anybody tell me what to do to get both values, so that i am able to work with them?
According to the man page, if you're using mysqli_multi_query, you can access results from the different queries like so:
To retrieve the resultset from the first query you can use mysqli_use_result() or
mysqli_store_result(). All subsequent query results can be processed using
mysqli_more_results() and mysqli_next_result().
They give some sample code:
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
You can't use 2 query . Use combine query like this
$query .=" SELECT * , COUNT(PRESENT),COUNT(lesson) FROM seventh_a";
$query .=" WHERE class ='0' AND NAME ='Alexander Kirkby Scherer'";
$query .=" AND PRESENT = 'TS' GROUP BY lesson";
you will get your result $row['COUNT(PRESENT)'] and $row['COUNT(lesson)']
OR use mysqli's multi_query function for this add ; between queries like this
$query .=" SELECT * , COUNT(PRESENT) FROM seventh_a";
$query .=" WHERE class ='0' AND NAME ='Alexander Kirkby Scherer'";
$query .=" AND PRESENT = 'TS' GROUP BY lesson;"; // semicolon here
$query .= " SELECT * , COUNT(lesson) FROM seventh_a";
$query .=" WHERE class ='0' AND NAME ='Alexander Kirkby Scherer'";
$query .=" GROUP BY lesson";

Categories