PHP SQL Query for autocomplete - php

I have a MySqL DB with a table of Properties NAMES(can be more then one word) and I want to run a query to get results for the user text inputs to use for an autocomplete field.
The query I currently use is:
$query = "SELECT * FROM table WHERE LOWER(name) LIKE '%$value%' LIMIT 7";
But it is not good enough.
I tried splitting the input $value but for some reason is not working:
$values = explode(" ", $value);
$str = "";
for($i = 0; $i < count($values); ++$i)
{
if( $i == 0)
$str .= "LOWER(name) LIKE '%&$values[$i]%' ";
else
$str .= "AND LOWER(name) LIKE '%$values[$i]%' ";
}
$query = "SELECT * FROM table WHERE ". $str . " LIMIT 7";
Do you have any suggestions?
TX in advance.

Do OR instead of AND in your query:
$str .= "OR LOWER(name) LIKE '%$values[$i]%' ";

Related

Search more then one MySql table in Mysql Database PHP

I have a database have 20 tables I want to search all of these I got stuck that how can I search this and solve this query help is very appreciated. Like:
table1
table2
table3
table4
and so one. This is my script.
<?php
if(isset($_GET["search"]))
{
$condition = '';
//$query = explode(" ", $_GET["search"]);
$query = explode(" ", $_GET["search"]);
foreach($query as $text)
{
$condition .= "`title` LIKE +'%".mysqli_real_escape_string($connect, $text)."%' OR ";
}
$condition = substr($condition, 0, -4);
$sql_query = "SELECT * FROM countries2 WHERE " . $condition;
$result = mysqli_query($connect, $sql_query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
echo '<tr><td>'.$row["title"].'</td></tr>';
}
}
else
{
echo '<label>Data not Found</label>';
}
}
?>
Try with this
sql_query = "SELECT * FROM `countries`,`countries2` WHERE " . $condition;
i have noticed that you are making a search directory or something like this.
you may use FULLTEXT SEARCH with operators and Stemming
after this your query will look like this.
implement as per your requirement ;).
(SELECT * FROM table1 WHERE(col1,col2,clo3) AGAINST(."$search".) IN NATURAL LANGUAGE MODE)

SQL search using PHP arrays

How to search multiple fields in a MySQL database with a PHP array.
For example, search fields like place_name, admin_name1, and admin_name2 using an array of ["Cambridge","Massachusetts","US"] with using the wildcard %
Below is the exact structure of database
Imagining your array index names are the same as your table column names:
$query = "select * from tableName";
$arrCount = count($arrName);
$i=1;
if($arrCount) > 0){
$query .= " where";
foreach($arrName as $key->$val){
$query .= $key." LIKE '%".$val."%'";
if($i <= $arrCount)
$query .= " AND";
$i++;
}
}
Then run the query!
$array = ["Cambridge","Massachusetts","US"];
$list = implode(",", $array);
Then select:
... WHERE place_name IN($list) OR admin_name1 IN($list) OR admin_name2 IN($list)
Try this
$fields = array("place_name", "admin_name1", "admin_name2");
$kwd = array("Cambridge","Massachusetts","US");
$condition = array();
$n = 0;
foreach($fields as $field){
$condition[] .= $field." LIKE '%".$kwd[$n]."%'";
$n++;
}
$condition = implode(" AND ", $condition);
echo $qry = "SELECT * FROM `table` WHERE ( ".$condition." )";

How to order by first name (SQL) in an exploded string

I have the following code to search for a name in a field that has all three name so I have been forced to explode the string for better results as follows
$search_terms = explode(" ", $key);
$count = count($search_terms);
$tick= 0;
$query = "";
for($i = 0; $i < $count; $i++) {
$tick++;
$query .= "SELECT * ";
$query .= "FROM agents ";
$query .= "WHERE names ";
$query .= "LIKE '%".$search_terms[$i]."%' ";
$query .= "OR company LIKE '%".$search_terms[$i]."%' ";
if($tick != $count)
$query .= " UNION ";
}
$query .="ORDER BY names ASC ";
The problem is that once a search query such as Lawrence Gabriel and my database does indeed have Lawrence Gabriel but also Edward Gabriel, I will get the Edward result listed before Lawrence.
I'd like to have all 'Gabriels', so to speak, listed but for my results to be ordered by the first name typed into the search box. This would have been easier if first name, second name were in individual columns.
How can I achieve the desired result?
try this
ORDER BY SUBSTRING_INDEX(names, ' ', 1) ASC
this will order by the first name before the space
Demo
you can use it like that also:
SELECT id, names, SUBSTRING_INDEX(names, ' ', 1) name
FROM agents
WHERE names
LIKE '%".$search_terms[$i]."%'
OR company LIKE '%".$search_terms[$i]."%'
ORDER BY name asc
DEMO

PDO - Search is querying terms as whole rather than each term separately

I currently have a simple search engine which searches a column in my database based on input from a user:
$search = $_GET['search'];
$terms = explode(" ", $search);
$sql = "SELECT * FROM people WHERE lname LIKE :search";
$q = $conn->prepare($sql) or die("failed!");
$q->bindValue(':search',"%".$search."%",PDO::PARAM_STR);
$q->execute();
if ($q){
//
do something
}
Currently it is searching for terms as a whole, for example "red desk" returns a result BUT "desk red" does not return anything
Any ideas? Any help much appreciated!
EDIT:
I have since changed it to this...
$search = $_GET['search'];
$terms = explode(" ", $search);
$sql = "SELECT * FROM people WHERE MATCH (lname,fname) AGAINST (:search IN BOOLEAN MODE)";
$q = $conn->prepare($sql) or die("failed!");
$q->bindValue(':search',"%".$search."%",PDO::PARAM_STR);
$q->execute();
it seems to be working okay for now, if anyone could suggest a better solution i would be very thankful!
This might not be the best way but I think something like this might do the job. I would myself love to know if there's a smarter way to do this!
$search = $_GET['search'];
$terms = explode(" ", $search);
$sql = "SELECT * FROM people"
if(count($terms) > 0) {
$sql .= " WHERE (lname LIKE '%:term_0%' OR fname LIKE '%:term_0%')";
for($i = 1; $i < count($terms); $i++)
$sql .= " AND (lname LIKE '%:term_" . $i . "%' OR fname LIKE '%:term_" . $i . "%')";
}
$q = $conn->prepare($sql) or die("failed!");
for($i = 0; $i < count($terms); $i++)
$q->bindValue(':term_' . $i, $terms[$i]);
$q->execute();

For loop getting out of control?

I have put together a for loop for a small search function I am building.
The code is as follows
$keyword = explode("+", $keywords);
for($i=0; $i <= count($keyword); $i++){
//check user table
$q = "SELECT id, username FROM ".TBL_USERS." WHERE username LIKE '%$keyword[$i]%'";
$result = $database->query($q);
while($row=mysql_fetch_assoc($result)){
extract($row);
echo "<a href='/profile.php?id=$id'>$username</a>";
}
}
When this runs, it is somehow retrieving all of the users from the database.
Is there any obvious reason for this?
If $keywords = "gregg"; , would this still work as there wouldn't be a + sign (only one word). Either way, this still doesn't work when it has multiple words involved!
I can confirm the query works perfectly if the term 'gregg' is passed into it.
Thanks for reading, hope you can help.
Your for loop looks like:
for ($i=0; $i <= count($keyword); $i++)
This is going past the end of $keyword by one, so the last query the loop executes is "LIKE '%%'" which would return every row. To fix this, change it to:
for ($i=0; $i < count($keyword); $i++)
Also, you cannot do "$keyword[$id]". It must be "{$keyword[$i]}"
your index has count($keyword) - 1, not count($keyword);
$keyword = explode("+", $keywords);
for($i=0; $i <= count($keyword) - 1; $i++){
//check user table
$q = "SELECT id, username FROM ".TBL_USERS." WHERE username LIKE '%".$keyword[$i]."%'";
$result = $database->query($q);
while($row=mysql_fetch_assoc($result)){
extract($row);
echo "<a href='/profile.php?id=$id'>$username</a>";
}
}
and changed quotes
try this
$q = "SELECT id, username FROM ".TBL_USERS." WHERE username LIKE '%{$keyword[$i]}%'";
or better this
$q = "SELECT id, username FROM ".TBL_USERS." WHERE username LIKE '%" . $keyword[$i] . "%'";
Consider use OR in the sql:
$keyword = explode("+", $keywords);
$keywords = array_map("mysql_real_escape_string", $keywords);
$q = "SELECT id, username FROM user WHERE username LIKE '%" . implode("%' OR username LIKE '%", $keywords) . "%';";
$result = $database->query($q);
while($row = mysql_fetch_assoc($result))
{
extract($row);
echo "<a href='/profile.php?id=$id'>$username</a>";
}

Categories