Reputation: 25
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.
Upvotes: 2
Views: 41
Reputation: 2155
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
Upvotes: 0
Reputation: 5326
Use the following query:
$sql = "SELECT * FROM `tws` WHERE `tags` REGEXP (".$name.")";
Upvotes: 1
Reputation: 2536
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"
)
Upvotes: 0
Reputation: 11806
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.
Upvotes: 0