I have a table names
and in that table there is a field info
data is like this:
ID info
1 'alpha,romeo,ciera,delta'
2 'testing,temp,total'
I am trying to create a select query.
select * from names where info like '%$var%'
$var
is data from php.
Problem is i want exact match. If i use above query and in $var if data is
rome
then it also return row of romeo.
one more example-
data in table is testing,temp,total
user input data is test
then it also return testing
i tried
select * from names where info like '$var%'
and
select * from names where info like '%$var'
but it didn't return data as i expected.
Please advise how can i achieve this.
Note- : This is an example i am not using mysql as its depreciated. I am using mysqli
Append ,
at begin and end of your target search string.
And then make sure your source string also has those ,
select *
from names
where concat( ',', info , ',') like
concat( '%,', $var, ',%')
The problem is this wont use any index. You should go for FULL TEXT
search
Use ,
in your query to use it as a delimiter and use multiple conditions to account for the "edge cases".
SELECT *
FROM names
WHERE
info LIKE '%,$var,%' OR
info LIKE '$var,%' OR
info LIKE '%,$var' OR
info = '$var'
If you have rows with info
column:
alpha,romeo,ciera,delta
testing,temp,total
rome
foo,test,bar
berlin,paris,madrid,london,rome
venice,milano,rome,firence
black,crome
rome,fome,mome,kome,kome
Query with $var
as "rome"
will select:
rome
berlin,paris,madrid,london,rome
venice,milano,rome,firence
rome,fome,mome,kome,kome
But not:
alpha,romeo,ciera,delta
black,crome
Problem is i want exact match. If i use above query and in $var if data is rome then it also return row of romeo.
Don't use the LIKE
operator, use exact match operator =
select * from names where info = '$var'