I'm having trouble with a search query.
I have two columns named 'artist' & 'title'. But for an autocomplete function I need a SQL query to search in these columns while someone is typing. There is a very simple solution I know of which is the following:
SELECT * FROM music WHERE artist LIKE '%".$term."%' OR title LIKE
'%".$term."%'
$term = textboxvalue
But this query has a couple of huge problems. Let's say the artist is 'DJ Test' and the title is 'Amazing Test Song'. If I type 'DJ' it works fine. But when I type 'DJ Amazing'. No search results were found. Obviously ofcourse but I can't figure how to fix it.
But that's not the only problem. If someone types in 'DJ Test - Amazing Test Song' it has to ignore the '-'.
So my question is, what does my search query look like when I can type anything like 'Amazing DJ Test' and still give back what I need?
Try something like this.
I think it should work but I haven't tested it.
$terms = explode(' ', $term);
foreach($terms as $term){
$query = SELECT * FROM music WHERE artist LIKE '%".$term."%' OR title LIKE '%".$term."%'
return $query;
}
Should hopefully work
You would have to make it split the search string up into words, then add those words as lookup criteria by appending them to the query.
First make an array that contains each individual word from the search string.
$search = 'DJ TEST Amazing Test Song';
$search_terms = explode(" ", $search);
Then alter the query for each search term:
foreach($search_terms as $search_term) {
//append OR to query with $search_term
$query .= "OR artist LIKE '%".$search_term."%' OR title LIKE '%".$search_term."%'";
}
Related
I recently added search box to search certain data on my database.
Im using php LIKE function.for the first time when i use LIKE function it took only one word and if that match any of contents then the results came out.and if i type more than one word it came zero results and it return a error that "No results".
And as i did a research i made my code it to thing.(Now it is allways searching only for the last word on the sentence that we enter for search.)]
In a example :
If type "car for sell" the query going to search for "Sell" .If there are any records match the query then it will exicutue (weather it is car or any other data.)
what i want to do iss to let it search for complete search where it matchs in the database.
For a example :
if i want to find "car for sell"
i want the query to execute only cars for sell in my cars category and so on.
here are my codes.
$getquery = $_GET['query'];
if(isset($_GET['query'])){
$getquery = $_GET['query'];
$queryexplode = explode(" ", $getquery);
foreach($queryexplode as $queryexplodenew){
$meta = $queryexplodenew;
}
$getdataquery = "SELECT `AdName`, `AdAccessLink`, `timestamp`, `Country`, `Category`, `Price`, `Photo1name` FROM freeadpostingdata WHERE AdName LIKE '%$queryexplodenew%' OR Country LIKE '%$queryexplodenew%' OR Category LIKE '%$queryexplodenew%' OR AdDescription LIKE '%$queryexplodenew%' ORDER BY timestamp DESC LIMIT 0, 25";
$resultsgetdata = mysql_query($getdataquery);
$countprodu= mysql_num_rows($resultsgetdata);
}
please help me to get this solved.
thank you
The reason you are only searching for the last word is because of this:
$queryexplode = explode(" ", $getquery);
foreach($queryexplode as $queryexplodenew){
$meta = $queryexplodenew;
}
You are iterating over each word in the query with each word being put in $queryexplodenew in turn (and then assigned to $meta for some reason). When the loop completes, the thing in $queryexplodenew will be the last element iterated over.
Yes, for your code, it will always search for the last word.
$getquery = $_GET['query'];
$modifiedKeyword = explode(" ", $getquery);
$str = implode("', '", $modifiedKeyword );
And change your query like the following:
$sql = "SELECT id FROM your_table WHERE keyword IN ('$str')";
I hope it will work for you.
I have a filter in my mvc model which takes a variable from a search field. It searches titles, among other things, but the search results are poor. This may be a simple syntax problem, but I couldn't see it searching.
I have some item titles like:
"Manolo Blahnik Carolyne Gold Glitter Slingback Pump (35.5, Gold)"
or
"Belstaff Trialmaster Jacket"
Currently if you search for "manolo blahnik shoes" or "belstaff jacket" you get no results.How do I get matching on ANY of the words from any part of the string?
I have tried adding % to either side of the variable like this %'.$keyword.'% but that doesn't work.
//Filtering search field
$jinput = JFactory::getApplication()->input;
$keyword = $jinput->get('keyword', '', 'NULL');
if($keyword!=''){
$keyword = $db->Quote('%' . $db->escape($keyword, true) . '%');
$query->where('( a.title LIKE '.$keyword.' OR a.features LIKE '.$keyword.' OR a.brand LIKE '.$keyword.' )');
}
i think your best bet would be then to explode the search sting you get and create OR's from them
so
$keyword = "manolo blahnik shoes";
$keyWords = explode(' ', $keyword);
$ors = array();
foreach($keywords as $word) {
$word = $db->Quote('%' . $db->escape($word, true) . '%');
$ors[] = "a.title LIKE %word";
$ors[] = "a.features LIKE $word";
$ors[] = "a.title brand LIKE $word"
}
$queryString = implode(' OR ', $ors');
$query->where($queryString);
Since just one of the words should be in just one of the 3 columns you can have a whole string of OR's.
Of course this can become a rather large query so maybe that is something you would have to keep in mind.
Also this code is an example that you can change to your needs for example make sure that $keywords is not empty before you explode ,escape the keywords that you get or use a prepared statement to prevent sql injection things like that.
For something like this it might even be wise to look into solr for your search instead of doing it directly with mysql. Or if you have a myisam table you might look into FULL TEXT search mysql FULLTEXT search multiple words
so I have a blog system, and i want to build a section for "related news", I am not making a 'Tags' system but just simply searching and storing the current title of the article (which is pulled from the database) in a string and exploding it to be able to later put all the words into a query, that later query will search all titles in the database to find any of those words, and if it does, it will return the title in a list. Here is the relevant code:
// note to stackoverflow peeps, $row_object_title is just the title that is pulled form the database
$row_object_title_lower = strtolower($row_object_title);
$keywords = explode(" ",$row_object_title_lower);
Code that is run later on the page:
$keywords_imploded = implode("','",$keywords);
$myquery = sql_query("SELECT object_title FROM table WHERE object_title IN ('$keywords_imploded')
Now i try to list the titles by printing the title out, but nothing is display.
I am sure there is matching titles in the database.
Thanks
Your array of keywords is generated with:
$keywords = explode(" ",$row_object_title_lower);
What if you have a title like "My Super Blog Post"? You're going to get:
$keywords = array( "My", "Super", "Blog", "Post" );
Later on, you query using those values imploded together:
$keywords_imploded = implode("','",$keywords);
$myquery = sql_query("SELECT object_title FROM table WHERE object_title IN ('$keywords_imploded')
The SELECT query is going to look like this:
SELECT object_title FROM table WHERE object_title IN ( 'My', 'Super', 'Blog', 'Post' );
I don't think that's going to find anything.
You need to re-evaluate how you're handling the list of titles (I think that's what you're going for, right?).
It seems as though you have misunderstood how the IN clause works.
The IN clause will look for what is on the left in the list of values on the right. For example: WHERE id IN (2,3,5) - if id is in that list it will return true. In your case it is the opposite.
Something like this should work for what your after but there are likely to be better alternatives.
$sql = '';
foreach ($keywords AS $keyword)
{
if ($sql != '')
$sql .= ' OR ';
$sql .= "object_title LIKE '%$keyword%'";
}
$query = 'SELECT object_title FROM table WHERE '.$sql;
% is a wildcard.
Just please remember to escape the values first.
Try:
$keywords_imploded = join("','", $keywords);
$myquery = sql_query("SELECT object_title FROM table WHERE object_title IN ($keywords_imploded)
I'm trying to create a search engine in php and mysql. The search engine should be able to accept multiple value and display all possible result, i checked this thread php/mysql search for multiple values, but i need to use global variable at the place where LIKE '$search%' is. This is how my sql statement looks like,
SELECT name FROM product WHERE name LIKE '%$search%
the variable search is declared correctly,now everything works fine when i search specifically, such as Gold chain will show Gold chain.But when i search another name together such Gold Chain Shirt,where shirt is another product's name,the result is not showing. How should i change my sql command to get multiple result from multiple value searched? I'm very sorry i did not tell earlier that i was asked to do it in 3 tier programming.
There's a decent article here which will give you a decent introduction to searching MySQL with PHP, but basically what you want to do is split your search phrase in to parts and then use them in the MySQL query. For instance:
<?php
$search = 'Gold Chain Shirt';
$bits = explode(' ', $search);
$sql = "SELECT name FROM product WHERE name LIKE '%" . implode("%' OR name LIKE '%", $bits) . "%'";
The above will generate this query:
SELECT name FROM product WHERE name LIKE '%Gold%' OR name LIKE '%Chain%' OR name LIKE '%Shirt%'
You really need to look at FULLTEXT indexing, then read about FULLTEXT Query Expressions.
If I understood you correctly, you want to search all items that have value "Gold Chain" or "Shirt". In this case, as you tag the question as "php", you could do this by changing the $search as the whole WHERE clause. I do this such way (example with showing different conditions to explain the idea):
$search_array=array('name LIKE "%Gold Chain%"', 'price > 5');
$where=implode($search_array,' OR '); // you might wish ' AND '
some_function_to_query('SELECT name FROM product WHERE '.$where);
You could improve your search by doing :
'%$search' to search only from the beginning of the String to get more results.
Than, if you wanted to search each word from a sentence, you could do like that :
$search = 'Gold Chain Shirt';
$searches = explode(' ', $search);
$query = "SELECT * FROM product WHERE name ";
foreach($searches as $word) {
$query .= "LIKE '%{$word}' OR ";
}
Right now I'm just using a simple
WHERE name LIKE '%$ser%'
But I'm running into an issue - say the search is Testing 123 and the "name" is Testing, it's not coming back with any results. Know any way to fix it? Am I doing something wrong?
If you want to search for 'Testing' or '123' use OR:
WHERE (name LIKE '%Testing%' OR name LIKE '%123%')
Note however that this will be very slow as no index can be used and it may return some results you didn't want (like "4123"). Depending on your needs, using a full text search or an external database indexing product like Lucene might be a better option.
That's how LIKE works - it returns rows that completely contain the search string, and, if you use "%" optionally contain something else.
If you want to see if the field is contained in a string, you can do it this way:
SELECT * FROM `Table` WHERE "Testing 123" LIKE CONCAT("%",`name`,"%")
As Scott mentioned, you cannot check to see if the search contains the column value, it works the other way round.
so if $ser = "testing" and table has a row name = testing 123 it will return
For what you're trying to do you'll need to tokenize the search query into terms and perform an OR search with each of them or better still check out mysql full text search for a much better approach
After the variable $ser is replaced, the query is:
WHERE name LIKE '%Testing 123%'
You should build the query separating by words:
WHERE name LIKE '%$word[1]%$word[2]%'
not efficient (as your example) but working as you want:
WHERE name LIKE '%$ser%' OR '$ser' LIKE CONCAT('%', name, '%')
As mentioned by Mark and others, a full text search method may be better if possible.
However, you can split the search string on word boundary and use OR logic—but check for the whole string first, then offer the option to widen the search:
NOTE: Input sanitization and preparation not shown.
1. Query with:
$sql_where = "WHERE name LIKE '%$ser%'";
2. If zero results are returned, ask user if they would like to query each word individually.
3. If user requests an 'each word' search, query with:
$sql_where = get_sql_where($ser);
(Working) Example Code Below:
$ser = 'Testing 123';
$msg = '';
function get_sql_where($ser){
global $msg;
$sql_where = '';
$sql_where_or = '';
$ser = preg_replace("/[[:blank:]]+/"," ", trim($ser)); //replace consecutive spaces with single space
$search_words = explode(" ", $ser);
if($search_words[0] == ''){
$msg = 'Search quested was blank.';
}else{
$msg = 'Search results for any of the following words:' . implode(', ', $search_words);
$sql_where = "WHERE name LIKE '%$ser%'";
foreach($search_words as $word){
$sql_where_or .= " OR name LIKE '%$word%'";
}
}
return $sql_where . $sql_where_or;
}
$sql_where = get_sql_where($ser);
//Run query using $sql_where string