Php search with multiple words - php

So, I have defined a function for searching from DB and passing the results to ajax.
function do_search() {
$search=$_POST['dname'];
global $wpdb;
$sql="SELECT * FROM employee WHERE `firstname` LIKE '%{$search}%' OR `lastname` LIKE '%{$search}%' OR `department`LIKE '%{$search}%' OR `phone` LIKE '%{$search}%' OR `job_title` LIKE '%{$search}%' OR `cell_phone` LIKE '%{$search}%' OR `image`LIKE '%{$search}%' OR `email` LIKE '%{$search}%' OR `address` LIKE '%{$search}%' OR `room` LIKE '%{$search}%';";
$result2=$wpdb->get_results($sql);
echo json_encode($result2);
wp_die();
}
But my problem is its working only with one word. I tried explode the $_POST value with " ". and then making foreach and build multiple queries, like $query[i] but i cant get no response?
How do implement that when echoing the result - then it echoes result where every word is compared to those field entries?

Instead of exploding search query and producing tons of conditions, You can use simple "trick":
$search = $_POST['dname'];
$search = str_replace(' ', '%', $search);
$query = "SELECT * FROM yourTable WHERE col1 LIKE '%{$search}%' OR col2 LIKE '%{$search}%' ";
Don't forget to escape input or parametrizing query.

Exploding and multiple query criterias is the only option here.
this is wrong to say that making a $search variable like this will make it multi word searching the same column. It will not. Because the result of spaces replaced with pecentage wild card will be something like %word1%word2% using above code and multiple percentages will make it search BOTH words not a single one, in that particular column, so multiple percentage wildcards are treated in SQL as AND meaning both should meet in order to be selected, whereas I think we are trying to create a multi word query that treats as OR meaning either word1 or word2 exist, the record should be selected (hence requirement for explode and as many likes required as many words user entered), no this trick of replacing spaces with pecentages, will not work in multiple words.

Related

Php search query exact word match with CONCAT

I am trying to build a search query where suppose if we type a word stem, it should show words starting with stem and whatever follows after that. Right now, my code looks like this:
$sql = "SELECT * FROM `faculty`
WHERE (CONCAT(`firstName`, ' ', `lastName`,`expertise`,`affiliation`)
LIKE '%$textSearch%') ORDER BY lastname asc";
If I search stem in the search bar, it will show unneccessary words like 'System'.
If you’re looking for a search across multiple columns, but each word must begin with the search term you may have to make it a multiple LIKE statement?
$sql = "SELECT * FROM `faculty` WHERE
`firstName` LIKE ‘$textSearch%’ OR `lastName` LIKE ‘$textSearch%’ OR `expertise` LIKE ‘$textSearch%’ OR `affiliation` LIKE ‘$textSearch%’
ORDER BY lastname asc";

search without hyphen in mysql

Mysql database contains below kind of values :
'AE01-1056 Ricoh Aficio' OR 'Ricoh AE01-1087 (AE01-1069)' etc
AS if am a normal user i will search the product name in simple text like
AE011056 ... but the result is not found.
i hav tried this query:
$q="SELECT * FROM mytable WHERE (p.product_name LIKE '$name%' OR c.category_name LIKE '$name%' OR pm.name LIKE '$name%')";
What change should i make in my query to get the product , because i have tried LIKE operator & it's not working for me.
Use replace function
$q="SELECT * FROM mytable
WHERE (REPLACE(p.product_name,'-','') LIKE '%$name%'
OR REPLACE(c.category_name,'-','') LIKE '%$name%'
OR REPLACE(pm.name ,'-','') LIKE '%$name%')";
I think there are only two ways:
1. Manipulate search string
If you knwo, users are often search for a code and don't use nessesary hyphens, check the searchstring bevor searching if it follows a given format an insert the hypen if it is missing.
2. replace all hyphens in the where-statement
see http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_replace
Depending on your setup, solution one might be the more performant solution, since you only have to do one instead multiple stringmanipulations.

Retrieving data from string(tags)

The script fetches input from user and searches database field, named tags.
tags contains data for eg: hello, hey, how , happy, hell .. on single cell or you may say as a string.
i tried the query below, but it only works for hello and not for how , happy, hell..
$sql ="SELECT * FROM tws where tags='".$name."' or tags LIKE '".$name.",%' or tags LIKE
',%".$name.",%' or tags LIKE '%,".$name."'";
Note: I thoroughly searched google and stack overflow before posting this question but couldn't get it to work.
Use the following query:
$sql = "SELECT * FROM `tws` WHERE `tags` REGEXP (".$name.")";
You have one percent-sign placed wrong (the third LIKE) and MySQL is quite strict: you have to include the spaces between your tags in the SQL:
$sql ="SELECT * FROM tws where tags='".$name."' or tags LIKE '".$name.",%'
or tags LIKE '%, ".$name.",%' or tags LIKE '%, ".$name."'";
should work (remove the space after how, so your data has a fixed format).
PS: Make sure you use mysql(i)_real_escape_string to escape the value $name
Consider using an extra table where you store your tags. e.g. tws_tags, with fields tws_id and tag and a query with a JOIN on that.
You should omit the commas in your query like this:
$sql ="SELECT * FROM `tws` WHERE `tags` RLIKE '%[[:<:]]$name[[:>:]]%'";
[[:<:]] and [[:>:]] are special markers in MySQL for word boundaries. Alse, in double quotes you can use variables without having to concatenate ("blablabla $smth txt" instead of "blablabla " . $smth . " txt")
Use this:
$sql ="SELECT * FROM tws where tags='".$name."' or
tags LIKE '".$name."%' or tags LIKE
'%".$name."%' or tags LIKE '%".$name."'";
Here your query looks like below if name = ABC
$sql ="SELECT * FROM tws where tags='ABC' or tags LIKE 'ABC,%' or tags LIKE
',ABC,%' or tags LIKE '%,ABC'";
You can see that it is looking for ,ABC not only for ABC

having trouble search through mysql database

I have two questions regarding my script and searching. I have this script:
$searchTerms = explode(' ', $varSearch);
$searchTermBits = array();
foreach($searchTerms as $term){
$term = trim($term);
if(!empty($term)){
$searchTermBits[] = "column1 LIKE '%".$term."%'";
}
}
$sql = mysql_query("SELECT * FROM table WHERE ".implode(' OR ', $searchTermBits)."");
I have a column1 with a data name "rock cheer climbing here"
If I type in "rock climb" this data shows. Thats perfect, but if I just type "Rocks", it doesn't show. Why is that?
Also, How would I add another "column2" for the keyword to search into?
Thank you!
Searching that string for "rocks" doesn't work, because the string "rocks" doesn't exist in the data. Looking at it, it makes sense to you, because you know that the plural of "rock" is "rocks", but the database doesn't know that.
One option you could try is removing the S from search terms, but you run into other issues with that - for example, the plural of "berry" is "berries", and if you remove the S, you'll be searching for "berrie" which doesn't get you any further.
You can add more search terms by adding more lines like
$searchTermBits[] = "column1 LIKE '%".$term."%'";
and replacing ".$term." with what you want to search for. For example,
$searchTermBits[] = "column1 LIKE '%climb%'";
One other thing to note... as written, your code is susceptible to SQL injection. Take this for example... What if the site visitor types in the search term '; DROP TABLE tablename; You've just had your data wiped out.
What you should do is modify your searchTermBits[] line to look like:
$searchTermBits[] = "column1 LIKE '%" . mysql_real_escape_string($term) . "%'";
That will prevent any nastiness from harming your data.
Assuming the data you gave is accurate, it shouldn't match because you're using "Rocks" and the word in the string is "rock". By default mysql doesn't do case sensitive matching, so it's probably not the case.
Also, to avoid sql injection, you absolutely should be using mysql_real_escape_string to escape your content.
Adding a second column would be pretty easy as well. Just add two entries to your array for every search term, one for column1 and one for column2.
Your column1 data rock cheer climbing here your search criteria %Rocks% it doesn't fit at all as rocks is not in your column1 data
you can add column2 as you do for column1 then put it all together by using an AND operator (column1 LIKE "%rock%" OR column1 LIKE "%climb%") AND (column2 LIKE "%rope%" OR column2 LIKE "%powder%")
TIPS:
If your table/schema are using xx_xx_ci collation (then this is mean case insensitive,mysql doesn't care case sensitive) but if other then you need to make sure that the search term must be case sensitive(mysql do case sensitive).

Wildcard mysql LIKE or IN array values issue

I have the following code block which explodes a string upon spaces.
$run = explode(" ",strtolower($q));
eg. "This is the string"
Array $run look like:
(This,is,the,string)
The problems im having are:
I only want to explode the string if it has a white, something equal as using php function str_word_count($q)>1.
Unsure on how to create a single query which will work with multiple words in string and search table using any of them.
$query = "SELECT name FROM `table1` WHERE name LIKE '%". mysql_real_escape_string($run[0]) ."%' OR name LIKE '%". mysql_real_escape_string($run[1]) ."%'";
Trying to simplyfy the above query making it smaller and variable in size based on word count. Is this also a good aproach to exploding the string then preparing the sql?
I've tried using IN as well on SQL query with no good luck.
You can use MySQL's MATCH . . . AGAINST . . . to perform this kind of search:
WHERE MATCH (name) AGAINST ('this is the string')
Consult the documentation for more information.
Original solution, not helpful in this situation:
You can check out the MySQL specific function FIND_IN_SET:
WHERE FIND_IN_SET(colname, 'This,is,the,string') > 0
The value in colname cannot contain a comma, however.

Categories