Making a live search function - php

I've made a crud function where users register/log in to view their own contact list. The mysql database has tables of details such as name, mobile, email, company, title etc. I want to implement a live search function where the user can type in something such as e.g. first name + title or whatever random combination, and for the live search to be able to match the search field(s).
What is your recommendation in making something that fulfills the above?
Many thanks!

$result = array();
$Query = "SELECT * FROM contact_list WHERE ";
$keyword = preg_split("/[\s,-]+/", $q);
$flag = 0;
while ($flag<count($keyword))
{
if($flag==0)
$Query.=" name LIKE '%".$keyword[$flag]."%' OR title LIKE '%".$keyword[$flag]."%'";
else
$Query.=" OR name LIKE '%".$keyword[$flag]."%' OR title LIKE '%".$keyword[$flag]."%'";
$flag++;
}
$Query .= " ORDER BY `name` ASC";
$exec = $this->db->query($Query);
foreach ($exec->result() as $row)
{
array_push($result,$row);
}
This code i have done in codigniter. you can change it as you needed.. i hope this is you want.

Related

how can I select and display all the rows from the same user, underneath each other with php

Users can add their workouts into a database. There will have more than one workout per user. How can i display the workout names for the logged in user, underneath each other? I have no problem adding the workouts. When I echo the names of the added workouts, it display right next to each other like "workout1workout2". I want to be able to display the workouts underneath each other. I have no idea how to do it. It would be best if I could display each workout as a button.
$query = "SELECT * FROM info WHERE username='$_SESSION[username]' ";
$results = mysqli_query($db, $query);
while($data = mysqli_fetch_array($results)) {
echo $data['workout'];
}
Firstly, you shouldn't put that username in query like that. Look into SQL Injection and how to avoid that in PHP.
As for displaying buttons/workouts. You can embed HTML code inside the echo statement like below. You can add any html like that and it will render HTML.
$query = "SELECT * FROM info WHERE username='$_SESSION[username]' ";
$results = mysqli_query($db, $query);
while($data = mysqli_fetch_array($results)) {
echo "<button>$data['workout']</button></br>";
}
$query = "SELECT * FROM info WHERE username='$_SESSION[username]' Group By username";

Auto complete suggestion box are not working properly?

code:
<?php
include('config.php');
$return_arr = array();
$term = $_GET['term'];
$term = str_replace('.','',$term);
$sql = "SELECT * FROM submission where keyword like '%".$term."%' or companyname like '%".$term."%' ORDER BY CASE WHEN keyword LIKE '%".$term."%' THEN 1
ELSE 2 END";
$r = mysqli_query($link,$sql);
while($row = mysqli_fetch_assoc($r))
{
$key = explode(",", $row['keyword']);
foreach ($key as $keyword)
{
$return_arr[] = $keyword;
}
}
echo json_encode($return_arr);
?>
In my code I have created a auto complete suggestion box and its working but it always showing wrong result if I write (i) it always show result with (a) alphabet why not (i) and also want to search with short name. So, How can I do this ?Please help me.
Thank You
if you want to compare result start with input character then remove % from beginning
$sql = "SELECT * FROM submission where keyword like '".$term."%' or companyname
like '".$term."%' ORDER BY CASE WHEN keyword LIKE '".$term."%' THEN 1
ELSE 2 END";
You used %$term% in your query. So whether the data store the searched keyword anywhere in the string, it will display to you. So if you want to search the data start with a specific character remove % from the start of your query to make it as $term% as
$sql = "SELECT * FROM submission where keyword like '".$term."%' or companyname
like '".$term."%' ORDER BY CASE WHEN keyword LIKE '".$term."%' THEN 1
ELSE 2 END";

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')

How to make query that ignores undefined variables?

How make mysql search defined just by what is written in html form, by user, and if some form box is stayed empty, mysql should ignore it. For example:
$sql = "SELECT * FROM catalog WHERE name= '".$name."' AND publisher = '".$publisher."' ";
mysql_query($sql);
This query will display all rows where name and publisher are together. Now, what if user insert just name, and left publisher box empty. The idea is that php/mysql ignore empty form box, and display every row with inserted name. But it will not do that because $publisher will be undefined, and error emerges. How to tell musql to ignore $publisher? More generally, the question is: how to generate query that make searching defined by certain criteria if they exists, and if they don't how to just ignore it?
You can build up the sql programmatically. I am assuming you have escaped the values properly.
$sql = "SELECT * FROM catalog";
$wheres = array();
if (!empty($name)) {
$wheres[] = " name = '$name'";
}
if (!empty($publisher)) {
$wheres[] = " publisher = '$publisher'";
}
if (count($wheres)) {
$sql .= " WHERE " . implode (' AND ', $wheres);
}
//RUN SQL
Also have a read through this, you are using a deprecated mysql library.
This will allow either the name or the publisher to be NULL.
<?php
$sql = "SELECT * FROM catalog WHERE (name= '".$name."' OR name IS NULL) AND (publisher = '".$publisher."' OR publisher IS NULL)";
mysql_query($sql);
Try like
$my_var = " ";
if($publisher) //if(!empty($publisher))
$my_var = " AND publisher = '".$publisher."' ";
$sql = "SELECT * FROM catalog WHERE name= '".$name."' ".$my_var;
if the publisher is empty then you need to pass the NULL value and PLZ note that it is a bad practise.It will causes many sql injection issues.Try to put validations for the things

Rewrite query depending on GET parameters

I'm working on a search engine on my website. Users can add on criteria which is submitted with a GET in the url.
When users select for example 1 criteria, it looks like this:
localhost/search.php?course=1&price=&name=
They have 3 criteria they can select, so as you see he only selected COURSE.
Now I have to select from the database according to the criteria so my code looks like this:
if ($_GET['price'] > 0 && $_GET['name'])
{
$search_price = $_GET['price'];
$search_name = $_GET['name'];
$result2 = mysql_query("SELECT id, name, price, views, userid, type, anonymous FROM files WHERE course='$course_id' AND price < $search_price AND name LIKE '%$search_name%'");
}
elseif ($_GET['price'] > 0)
{
$search_price = $_GET['price'];
$result2 = mysql_query("SELECT id, name, price, views, userid, type, anonymous FROM files WHERE course='$course_id' AND price < $search_price");
}
elseif ($_GET['name'])
{
$search_name = $_GET['name'];
$result2 = mysql_query("SELECT id, name, price, views, userid, type, anonymous FROM files WHERE course='$course_id' AND name LIKE '%$search_name%'");
}
else
{
$result2 = mysql_query("SELECT id, name, price, views, userid, type, anonymous FROM files WHERE course='$course_id'");
}
while ($row2 = mysql_fetch_assoc($result2))
{
.....
But this can not be the correct way, because if eventually users can select 10 criteria this is going to be a very long code
How do I fix this?
What I would do is dynamically create the sql query,and then execute it at the end. So something like this
$query_string = "SELECT blahblah, blahblah, blah blah from blahx where 1=1 ";
$where = "";
if(isset($_GET['somecriteria']))
{
$where .= " AND blahblah = $_GET['somecriteia'] ";
}
if(isset($_GET['someOTHERcriteria']))
{
$where .= " AND blahblah=$_GET['someOTHERcritera'] ";
}
mysql_query($query_string . $where);
etc..
Take note this is just to show you how to achieve your objective. This is obviously prone to SQL Injection attacks and you'd have to clean the stuff up.
Use $_post to send larger amounts of information to the php script. When using get you should create the url to include get calls only if they are populated. As such if no price is selected the url should not include "price=". This will cause problems with your receiving script.
Your database script can be done with one call including only the selected criteria.
Myqsl has been depreciated, you need to look into Myqsli or PDO

Categories