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 ";
}
Related
I have looked for answers here in the community but I could not find anything specific. I have this page where I can search the name of users previously registered in my MySQL database. I am currently using the following statements:
PHP: $value = str_replace(' ', '%', $search);
SQL: "select * from user where name like '%".$value."%' order by name asc;"
The $search variable comes from a search form on this same page. (The above code allows me to make queries with more than one value). For example, considering a user named Luiz Henrique da Silva, if I search for Luiz, Luiz Henrique, or even Luiz Silva, this code will work perfectly, listing that user.
But my problem is: if I search the name out of order, such as Silva Henrique, or Silva Luiz, the user will not be listed. How could I enable this reverse search in a simple way?
Please note, using this code I am able to search separate values, thus my need is to make queries using disordered values!
PHP:
$value = str_replace(" ", "%' and name like '%", $search);
So using each word separately. But not safe: sql injection.
Using preg_replace caters for consecutive spaces:
$value = preg_replace('/\s+/', "%' and name like '%", $search);
$search = 'Jobs Steve';
$search = mysql_real_escape_string($search);
$where_condition = '';
$search_arr = explode(' ', $search);
foreach($search_arr as $key => $name) {
if ($where_condition != '') $where_condition .= ' AND ';
$where_condition .= " name LIKE '%$name%' ";
}
$sql = "SELECT * FROM user WHERE $where_condition ORDER BY name ASC;";
$sql will be like a SELECT * FROM user WHERE name LIKE '%Jobs%' AND name LIKE '%Steve%' ORDER BY name ASC;
It's a bad idea to inject unsanitized user input directly into a query because someone can execute their own queries and compromise your data/security. Look into prepared statements: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php.
As for your question, you could take the search that was provided, for example: Luiz Henrique, break it apart by whitespace so you get "Luiz" and "Henrique", then create a statement that looks something like:
WHERE name LIKE '%Luiz%' AND name LIKE '%Henrique%'
In this way you just keep adding AND LIKE statements for each individual component.
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
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."%'";
}
I am doing a query for an autocomplete function on a mysql table that has many instances of similar titles, generally things like different years, such as '2010 Chevrolet Lumina' or 'Chevrolet Lumina 2009', etc.
The query I am currently using is:
$result = mysql_query("SELECT * FROM products WHERE MATCH (name) AGAINST ('$mystring') LIMIT 10", $db);
The $mystring variable gets built as folows:
$queryString = addslashes($_REQUEST['queryString']);
if(strlen($queryString) > 0) {
$array = explode(' ', $queryString);
foreach($array as $var){
$ctr++;
if($ctr == '1'){
$mystring = '"' . $var . '"';
}
else {
$mystring .= ' "' . $var . '"';
}
}
}
What I need to be able to do is somehow group things so only one version of a very similar actually shows in the autosuggest dropdown, leaving room for other products with chevrolet in them as well. Currently it is showing all 10 spots filled with the same product with different years, options, etc.
This one should give some of you brainiacs a good workout :)
I think the best way to do this would be to create a new field on the products table, something like classification. All the models would be entered with the same classification (e.g. "Chevrolet"). You could then still MATCH AGAINST name, but GROUP BY classification. Assuming you are using MySQL you can cheat a little and get away with selecting values and matching against values that you are not grouping by. Technically in SQL this gives undefined results and many SQL engines will not even let you try to do this, but MySQL lets you do it -- and it returns a more-or-less random sample that matches. So, for example, if you did the above query, grouped by classification, only one model (picked pretty much at random) will show up in the auto-completer.
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