作为商场背景:
这是一个查询,我在字符串中寻找关键字。
我用“”空格爆炸字符串:
$words = explode(" ", $searchstring);
然后我用逗号分隔它们:
$commaSeparatedString = implode(", ", $words);
然后我执行查询:
$searchQuery = sprintf("SELECT * FROM solution T1 join solution_tags_intermediate T2
on T1.ID_SOLUTION = T2.ID_SOLUTION
join solution_tags T3 on T2.ID_SOLUTION_TAGS = T3.ID_SOLUTION_TAGS
WHERE T3.SOLUTION_TAGS_NAME IN '%s'", $commaSeparatedString);
我执行查询:
$resultSet = $DBConnect->query($searchQuery);
我收到以下错误:
Warning: Creating default object from empty value in C:\wamp\www\helpdesk\index.php on line 21
Fatal error: Call to undefined method stdClass::fetch_assoc() in C:\wamp\www\helpdesk\index.php on line 27
第21行是:
if($resultSet->num_rows = 0){ /*more code here*/}
而第27行是:
while($tableData = $resultSet->fetch_assoc()){/*print some stuff here*/}
据我所知,这是查询的正确语法,但phpmyadmin说它不是。这是我实际执行的查询:
SELECT * FROM solution T1 join solution_tags_intermediate T2
on T1.ID_SOLUTION = T2.ID_SOLUTION
join solution_tags T3
on T2.ID_SOLUTION_TAGS = T3.ID_SOLUTION_TAGS
WHERE T3.SOLUTION_TAGS_NAME IN 'internet, renweb'
phpmyadmin抛出的错误是:
#1064 - You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version
for the right syntax to use near ''internet, renweb' LIMIT 0, 30' at line 1
我做错了什么?我现在已经在这个项目上工作了8个多小时,我知道这很简单,但我无法弄清楚问题是什么。
答案 0 :(得分:4)
尝试此查询:
SELECT * FROM solution T1 join solution_tags_intermediate T2
on T1.ID_SOLUTION = T2.ID_SOLUTION
join solution_tags T3
on T2.ID_SOLUTION_TAGS = T3.ID_SOLUTION_TAGS
WHERE T3.SOLUTION_TAGS_NAME IN ('internet', 'renweb')
你这里也有问题:
if($resultSet->num_rows = 0){ /*more code here*/}
您需要使用比较符号==
,如下所示:
if($resultSet->num_rows == 0){ /*more code here*/}
答案 1 :(得分:3)
除了查询语法之外,这是一个问题。
if($resultSet->num_rows = 0){ /*more code here*/}
您将$resultSet
设置为等于0
!你需要在这里进行比较,而不是作业。
答案 2 :(得分:0)
$words = explode(" ", mysql_real_escape_string($searchstring));
$commaSeparatedString = "'".implode("','", $words)."'";
$searchQuery = sprintf("SELECT * FROM solution T1 join solution_tags_intermediate T2
on T1.ID_SOLUTION = T2.ID_SOLUTION
join solution_tags T3 on T2.ID_SOLUTION_TAGS = T3.ID_SOLUTION_TAGS
WHERE T3.SOLUTION_TAGS_NAME IN (%s)", $commaSeparatedString);
试试这个
答案 3 :(得分:0)
虽然@raygo的语法正确,但我想知道你是否应该使用IN
? IN
会查找T3.SOLUTION_TAGS_NAME
或internet
的{{1}}个值。
如果您实际上想要搜索renweb
包含所有这些条款以及任何顺序的结果,那么您希望进行如下查询:
T3.SOLUTION_TAGS_NAME
请记住,这不是一个非常有效的查询,也不能很好地使用索引,但对于小型数据集应该没问题。如果您有大量数据,那么您应该使用专用搜索系统。在我的公司,我们使用Apache Solr,但是如果需要,我只建议越过那个桥。
如果您需要一些PHP来帮助您使查询使用以下内容:
SELECT * FROM solution T1 join solution_tags_intermediate T2
on T1.ID_SOLUTION = T2.ID_SOLUTION
join solution_tags T3
on T2.ID_SOLUTION_TAGS = T3.ID_SOLUTION_TAGS
WHERE T3.SOLUTION_TAGS_NAME LIKE '%internet%'
AND T3.SOLUTION_TAGS_NAME LIKE '%renweb%'