php jquery json instant search - php

I'm trying to create an instant search to pull the data from my database.
I want it to be able to search 2 fields from 2 different tables. So far, I have it working that if you choose one specific field of either table, it will work just fine, currently; it is pulling the data and displaying it, but I want the search to be specific.
For example, let's say I have 2 tables, one is for artist, and the other one is for their records; when you type the name of the artist, it will show all the records form that artist, but if you type the date of the release alongside of the name, it will give you that specific record and it won't show others. That's how I want it to work.
Here's what I've got so far:
include 'conn.php';
$query = $_POST['query'];
$like = "'%$query%'";
$sql = mysqli_query($db, "SELECT * FROM users JOIN tshift ON users.id=tshift.uid WHERE name LIKE {$like}
LIMIT 6");
$arr = array();
while ($r = mysqli_fetch_assoc($sql))
{
$results= array();
foreach($r as $key => $val){
if(is_string($key))
$results[$key] = $val;
}
array_push($arr, $results);
}
echo json_encode(array("artist" => $arr,"album" => $arr,"release" =>$arr));

for those that wonder or will wonder one day how to do something like this, this is how i got it to work i don't know if is the best way but it will do for now.
include 'conn.php';
$query = $_POST['query'];
$newQuery = explode("+", $query);
$name = "'%{$newQuery[0]}%'";
if(!empty($newQuery[1])){
$date = "'%{$newQuery[1]}%'";
}
if(empty($date))
{
$select = "SELECT * FROM users JOIN tshift ON users.id=tshift.uid WHERE name LIKE {$name}";
}
else
{
$select = "SELECT * FROM users JOIN tshift ON users.id=tshift.uid WHERE name LIKE {$name} AND udate LIKE {$date} ";
}
$sql = mysqli_query($db,$select);
$arr = array();
while ($r = mysqli_fetch_assoc($sql))
{
$results= array();
foreach($r as $key => $val){
if(is_string($key))
$results[$key] = $val;
}
array_push($arr, $results);
}
echo json_encode(array("artist" => $arr,"album" => $arr,"release" =>$arr));

Related

SQL SELECT Query use for search

I have three variables:
$school
$class
$subject
And a search String $searchquery
I want to search my database for the rows that match the Search Query... Currently I am using this:
$searchquery = str_replace(" ","|",$searchquery);
$sql = "
SELECT * FROM filedetails
WHERE school RLIKE '$searchquery'
OR class RLIKE '$searchquery'
OR subject RLIKE '$searchquery'";
Now, how this works, Suppose I enter Mathematics Class X. It converts the string into Mathematics|Class|X which is fine and search the Database and prints the results...
But there is one error:
It is printing all the rows which have either Mathematics or Class or X in them, so my output includes all the Classes of all Schools of Mathematics and All Subjects of All Schools of Class X...
Whereas I want it to show me All Schools having Mathematics and Class X...
P.S. - I have tried using AND instead of OR, but now I get empty result because no School Matches my Query String...
One way of doing is first make different 2-D Arrays of all the data searches and then take their intersection, so this will give the common row which matches all the keywords...
$sql = "SELECT * FROM filedetails";
$query = mysql_query($sql);
$array1 = array();
while ($row = mysql_fetch_array($query))
{
$array1[] = $row;
}
$sql = "SELECT * FROM filedetails WHERE school RLIKE '$searchquery'";
$query = mysql_query($sql);
$array2 = array();
while ($row = mysql_fetch_array($query))
{
$array2[] = $row;
}
$sql = "SELECT * FROM filedetails WHERE subject RLIKE '$searchquery'";
$query = mysql_query($sql);
$array3 = array();
while ($row = mysql_fetch_array($query))
{
$array3[] = $row;
}
$sql = "SELECT * FROM filedetails WHERE class RLIKE '$searchquery'";
$query = mysql_query($sql);
$array4 = array();
while ($row = mysql_fetch_array($query))
{
$array4[] = $row;
}
Now, what this code is doing that it is searching individually for every field and making separate result for each Query of each field, now We will be taking Intersection of the arrays so as to get the common row having the keywords
But there is one problem, suppose the $searchquery contains Details about School and Class, but no information about Subject, then the $array3 will be null, as the query will result NULL, then we need to consider handling null arrays which have been solved in Another Question Here...
Hope this helps... :)

for each statement only returns the word 'Array'

I'm creating a personal advisor page with 3 advisors in my database, I'm trying to create a dropdown box where someone can choose which advisor they'd like. At the moment my dropdown only displays the word 'Array' three times. Here's what I have so far.
<select name="advisor">
<?
$sqlQ = "SELECT concat(firstName,' ',lastName) FROM adv WHERE advisor IS NULL";
$array=array();
$res = $db->prepare($sqlQ);
$res->execute();
echo("<option>Advisor</option>");
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
$array[] = $row;
}
foreach($array as $info)
{
echo("<option>$info</option>");
}
Your $row is already an array, so no need to insert your $row into a new array. Just loop the results like this
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
foreach($row as $info)
{
echo("<option>$info</option>");
}
}
// give the result of concat() an alias so you can easily access it in the result set
$sqlQ = "SELECT concat(firstName,' ',lastName) as name FROM adv WHERE advisor IS NULL";
[...]
while ( $row = $result->fetch(PDO::FETCH_ASSOC) ) {
// $row is an array, its members correspond with the fields/aliases you've selected
// apply htmlspecialchars() so that the contents of $row['name'] can't break your html structure
echo '<option>', htmlspecialchars($row['name']), '</option>';
}

Sorting PHP arrays

I have three MySQL tables that I need to query for all of the rows. Upon getting all of the rows from each table, I need to create a multidimensional array whereby each index of that array contains only value from each of the tables. What I have right now works. But, something is telling me that there has got to be a better way of accomplishing this.
$tables = array('table_one', 'table_two', 'table_three');
$final = array();
foreach($tables as $table) {
$sql = "SELECT * FROM ".$table."";
$query = mysqli_query($con, $sql)or die(mysqli_error($con));
$num = mysqli_num_rows($query);
$i = 0;
while($row = mysql_fetch_array($query)) {
$id[$i] = $row['user_id'];
$i++;
}
for($i=0;$i<$num;$i++) {
if(!is_array($final[$i])) {
$final[$i] = array($id[$i]);
} else {
array_push($final[$i], $id[$i]);
}
}
}
The end results is something that looks like this
$final = array(array('table_one_row_one_val', 'table_two_row_one_val', 'table_three_row_one_val'),
array('table_one_row_two_val', 'table_two_row_two_val', 'table_three_row_two_val'),
array('table_one_row_three_val', 'table_two_row_three_val', 'table_three_row_three_val')
);
I get the gut felling that this could be done much more effectively, but I'm not sure how.
Thanks,
Lance
You can make your code simpler if you make your query more explicit in selecting the columns you want in the order you want them. So for example:
$sql = 'SELECT table_one.user_id as u1, table_two.user_id as u2, table_three.user_id as u3 FROM ' . implode(',', $tables);
Then each row of your result set will have the columns in the proper order making the construction of your arrays less involved. For example:
$query = mysqli_query($con, $sql)or die(mysqli_error($con));
while($row = mysql_fetch_array($query)) {
$final[] = array($row['u1'], $row['u2'], $row['u3']);
}
There may be issues with the order and relationships of the data in these arrays (especially if all 3 tables don't have the same number of rows), but working just off the information above, this is another way you could approach it. Something to think about anyway.
Try this:
$sql = "SELECT 'user_id' FROM ".$table;
What about:
$tables = array('table_one', 'table_two', 'table_three');
$final = array();
foreach($tables as $tableIndex => $table) {
$sql = "SELECT user_id FROM ".$table;
$query = mysqli_query($con, $sql)or die(mysqli_error($con));
$i = 0;
while($row = mysql_fetch_array($query)) {
$final[$tableIndex][$i] = $row['user_id'];
$i++;
}
}
It is always better selecting only the columns you will use. SELECT * is not a good SQL practice.

search entire table except date fields using mysql and php

I have a large table and would like to search all of the fields in one go but some of the fields are dates so the search I have created falls over when it hits those fields.
Is there a way to exclude certain types of fields when using this type of search?
$table = 'accounts';
$condition = 'tracey';
$sql = "SHOW COLUMNS FROM accounts";
$result = mysqli_query($mysqli,$sql);
if (mysqli_num_rows($result) > 0)
{
$i=0;
while ($row = mysqli_fetch_array($result))
{
if($i==0)
{
$q="select * from ".$table." where ".$row[0]." LIKE %".$condition."%";
}
else
{
$q.=" or ".$row[0]."="." LIKE %".$condition."%";
}
$i++;
}
}
$sql = $q;
$result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
$row = mysqli_fetch_array($result);
$answer = $row['phone_office'];
echo '<br><br>answer = '.$answer;
Or perhaps someone can suggest a better way of searching all of the fields in a table in one go?
To exclude certain types of fields You need to change the query SHOW COLUMNS FROM accounts with this one:
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE (table_name=".$table.")AND(NOT(DATA_TYPE IN ('field_type_1','field_type_2',...)));
Where field_type_i is the name of an excluded type (for example 'timestamp')

fetching and separating single column data from database

I am trying to display only user selected pages in dashboard
I have two columns in database like this
create table users(userid varchar(50), scripts varchar(100))
in userid column i will have the logged in user name and in scripts column, names of the pages which they want to display it in dashboard in comma separated format. ex: total, cust_orders,...
I want to fetch page name from scripts column separately like total.php, cust_orders.php...
i tried doing like this
$sql = "select scripts from users where userid = '".$_SESSION['UserID']."' ";
$result = DB_query($sql,$db);
$myrow = DB_fetch_array($result);
foreach ($myrow as $res)
{
$array123[] = $res;
$var123 = $array123[0];
$var222 = $array123[1];
}
but it wont work as the pages can be from 1 to 8, can somebody please help me in this?
EDITED
I have done like this
$result = DB_query($sql,$db);
$myrow = DB_fetch_array($result);
$arr= $myrow['scripts'];
$arr1 = explode(',', $myrow['scripts']);
print_r ($arr1);
and it worked, it displays like this
Array ( [0] => total_dashboard [1] => customer_orders [2] => unpaid_invoice [3] => lat
but dynamically how can i separate it and i have to add .php to this ...
$sql = "select scripts from users where userid = '".$_SESSION['UserID']."' ";
$result = mysql_query($sql,$db);
while($myrow = mysql_fetch_array($result))
{
$arr=explode(',',$myrow["scripts"]);//this will strip the , separated values in an array
//now you can fetch the scripts from database
}
You can use PHP - explode like:
while ($myrow = mysql_fetch_object($result))
{
// $myrow->scripts = "text1.php,text2.php,text3.php";
$scripts = explode(',', $myrow->scripts);
}
So $scripts will then contain each PHP-Page/Skript as own position in the array.
$scripts[0] = "text1.php";
$scripts[1] = "text2.php";
$scripts[2] = "text3.php";

Categories