检查与MySQL查询的字符串匹配

时间:2013-05-03 12:59:42

标签: php mysql

我试图从数据表中获取数据行,其中一个单词与我的专栏“故事”中文本中的单词匹配。

表格结构:

post_id | user_id | story
----------------------------------
1       | 1       | Hello World What's up?
2       | 4       | Hello guys!
3       | 7       | Working on shareit.me! 

例如:

我想抓住所有包含单词hello的帖子(我正在寻找不区分大小写的内容)。

我该怎么做?

这是我到目前为止所做的:

// this will be the keyword! so use the variable $filter_tag in the query!
$filter_tag= $_GET['tag'];

//query for getting the users' posts containing the select tag 
$query_posts= "SELECT * FROM posts WHERE user_id= '$user_id' ORDER BY post_id 
DESC";

$result_posts= mysqli_query($connect, $query_posts); 

谢谢!

7 个答案:

答案 0 :(得分:3)

 $query_posts= "SELECT * FROM posts WHERE user_id= '$user_id' AND story LIKE '%$filter_tag%' ORDER BY post_id 
    DESC";

答案 1 :(得分:1)

SELECT * FROM posts WHERE ... AND LOWER(story) LIKE '%hello%'

OR

SELECT * FROM posts WHERE ... 
AND story COLLATE latin1_general_ci_ai LIKE '%hello%'

答案 2 :(得分:0)

这将是:

SELECT * FROM posts WHERE ... AND story LIKE '%hello%'.

通常,“%”是通配符(如“*”)。所以你可以使用'hello%''%hello%'等等。

答案 3 :(得分:0)

您可以使用LIKE运算符:

$query_posts = "SELECT * FROM posts WHERE user_id = $user_id AND story LIKE '%yourword%' ORDER BY post_id";

%字符就像通配符。 %表示匹配任意数量的字符,其中_(下划线)只匹配一个。

注意:我也从user_id列检查中删除了单引号 - 这是一个整数,不希望用引号括起来 - 它们用于字符串。

答案 4 :(得分:0)

没有说不要忘记逃避输入。

$query_posts= "SELECT * FROM posts WHERE user_id = '$user_id' AND story LIKE '%".mysql_real_escape_string($filter_tag)."%'";

答案 5 :(得分:0)

我的回答是一样的,我做了一个方形的小说:

#supose the tag is Hello

SELECT * FROM posts
where story like "%Hello%";

PS:http://sqlfiddle.com/#!2/6bfcc1/5

答案 6 :(得分:0)

最好的解决方案是使用带有FULLTEXT索引的MATCH()AGAINST()。