Mysqli LIKE声明不起作用

时间:2013-08-13 02:57:28

标签: php mysqli

我遇到了这些奇怪的错误,我一直在编写代码,评论和重写,以及谷歌搜索所有的东西。 也许你们会看到我没有看到的东西:

$mysqli = new mysqli('host','login','passwd','db');
if($mysqli->connect_errno > 0){ die('Cannot connect: '. $mysqli->connect_error); }
// See if there is one term or multiple terms
if (count($search) == 1) {
// If one term, search for that
$like = $search[0];
$stmt = "SELECT 
            gsa_committees.id,
            gsa_committees.committee,
            gsa_committees.appointer,
            gsa_committees.representatives,
            gsa_committees.contact,
            gsa_committees.category,
            gsa_committees.attachments,
            gsa_committees.labels,
            gsa_committee_reports.committee,
            gsa_committee_reports.title,
            gsa_committee_reports.author,
            gsa_committee_reports.link,
            gsa_funds.id,
            gsa_funds.fund,
            gsa_funds.attachments,
            gsa_funds.labels,
            gsa_meeting_minutes.title,
            gsa_meeting_minutes.link,
            gsa_officers.office,
            gsa_officers.dept,
            gsa_officers.name,
            gsa_representatives.program_dept,
            gsa_representatives.representatives,
            gsa_representatives.alternate
        FROM 
            gsa_committees,
            gsa_committee_reports,
            gsa_funds,
            gsa_meeting_minutes,
            gsa_officers,
            gsa_representatives
        WHERE 
            (gsa_committees.committee LIKE $like) AND   
                             gsa_committees.committee IS NOT NULL";
}
if(!$result = $mysqli->query($stmt)){ die('Bad query: '. $mysqli->error); }

这给了我这个错误信息:

Bad query: 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 '%ARCHAC%) AND gsa_committees.committee IS NOT NULL' at line 34

我所知道的不是真的。如果我改变那个部分就是这样:

WHERE gsa_committees.committee LIKE $like";

我收到此错误消息:

Bad query: 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 '%ARCHAC%' at line 34

我看过的每个地方,字符串"%".search."%"似乎都是正确的方法,但我的服务器似乎不喜欢它。

有趣的注意事项:我在同一台服务器上的另一个页面上有一个不同的LIKE语句,由于某些原因这不会起作用。

谢谢!

4 个答案:

答案 0 :(得分:0)

尝试在搜索字词周围添加单引号($ like变量)。

例如:(gsa_committees.committee LIKE'$ like')

答案 1 :(得分:0)

您需要将变量包装在引号中以便工作:

WHERE gsa_committees.committee LIKE '$like';

请参阅String Comparison Function上的参考文档。

答案 2 :(得分:0)

看起来像缺少引号:

"WHERE gsa_committees.committee LIKE '$like' ";

答案 3 :(得分:-2)

好的,我明白了。这篇文章的答案解决了我的问题: MYSQLI SQL query over multiple tables fail

一旦我分配了表t1,t2等并进行了INNER JOIN,结果就会按预期进行,%$ search%或$ search。 谢谢大家!