PHP - mySQL“喜欢”查询什么都不返回

时间:2013-07-11 03:51:16

标签: php mysql

我知道这与其他很多帖子相同,但我无法理解!

我的代码如下:

$i=0;
$shelves = array();
$shelves['position'] = array();
$query = "select id, cat_id, book_title, writer, publisher, issue_year, copies, abstract from library where $table like '%$search_param%'";
$result = mysql_query($query);
while ( $data = mysql_fetch_assoc($result) ) {
   error_log($data['id']);
   $shelves['position'][$i]['id'] = $data['id'];
   $shelves['position'][$i]['cat_id'] = $data['cat_id'];
   $shelves['position'][$i]['book_title'] = $data['book_title'];
   $shelves['position'][$i]['writer'] = $data['writer'];
   $shelves['position'][$i]['publisher'] = $data['publisher'];
   $shelves['position'][$i]['issue_year'] = $data['issue_year'];
   $shelves['position'][$i]['copies'] = $data['copies'];
   $shelves['position'][$i]['abstract'] = $data['abstract'];
   ++$i;
}
error_log( count($shelves['position']) );

因为有其他帖子的音调,我尝试了他们的解决方案:

$query = sprintf("select id, cat_id, book_title, writer, publisher, issue_year, copies, abstract from library where %s like'%%%s%'",mysql_real_escape_string($table),mysql_real_escape_string($search_param) );

或类似的东西:

$query = "select id, cat_id, book_title, writer, publisher, issue_year, copies, abstract from library where $table like '%{$search_param}%'";

我也试过运行没有动态变量的查询只是文本而且我得到了同样的东西。

$query = "select id, cat_id, book_title, writer, publisher, issue_year, copies, abstract from library where book_title like '%lord%'";

似乎没什么用。

我已经在mysql workbench上测试了我的查询,它就像一个魅力!

在所有三个查询中,我从来没有得到第一个error_log的日志,第二个每次都对我大喊0!

有人可以照亮你的方式吗?

3 个答案:

答案 0 :(得分:2)

嗯,这里唯一可疑的是您使用的charset/collation,这可能会导致区分大小写问题。试试forcing a non-sensitive collation,看看会发生什么。

SET NAMES 'utf8' COLLATE 'utf8_general_ci';

utf8_bin(或任何* _bin)使比较区分大小写。如果将连接排序设置为不敏感的工作,这将解释您的脚本和MySQL Workbench之间的区别。

无论如何,我会将排序规则设置为不区分大小写以避免此类问题。

答案 1 :(得分:0)

The query getting correct answer.. 

Try this:

$i=0; // before start while loop,you need to initialize i

while ( $data = mysql_fetch_assoc($result) ) {
   error_log($data['id']);
   $shelves['position'][$i]['id'] = $data['id'];
   $shelves['position'][$i]['cat_id'] = $data['cat_id'];
   $shelves['position'][$i]['book_title'] = $data['book_title'];
   $shelves['position'][$i]['writer'] = $data['writer'];
   $shelves['position'][$i]['publisher'] = $data['publisher'];
   $shelves['position'][$i]['issue_year'] = $data['issue_year'];
   $shelves['position'][$i]['copies'] = $data['copies'];
   $shelves['position'][$i]['abstract'] = $data['abstract'];
   ++$i;
}

答案 2 :(得分:0)

试试这可能有所帮助。

$query ="select id,
                cat_id, 
                book_title,
                writer, 
                publisher, 
                issue_year, 
                copies, 
                abstract 
                from library 
                where ".$table." like "%".$search_param."%";

但它尚未经过测试。