我编写了一个函数,它应该返回受AND条件约束的对象。但它似乎只尊重最后的标准。例如,如果我查询" dog cat",它似乎返回包含" cat"的所有结果。无视" dog"。我究竟做错了什么?这是我的功能:
public function all($keyword, $offset = 0, $limit = 10) {
if(isset($keyword) && !empty($keyword)) {
$sql = 'SELECT id, date, title FROM wiki WHERE ';
$keywords = explode(" ", $keyword);
$i=0;
$count = count($keywords);
foreach($keywords as $word) {
$sql = $sql . '( lower(title) LIKE lower(:keyword' . $i . ') ) ';
if($i != $count - 1) $sql = $sql . "AND ";
$i++;
}
$sql = $sql . 'ORDER BY update_date DESC LIMIT :offset,:limit;';
$query = $this->db->prepare($sql);
for($i = 0; $i < count($keywords); $i++) {
$word = "%" . $keywords[$i] . "%";
$query->bindParam(":keyword$i", $word, PDO::PARAM_STR);
}
$limit = (int) $limit;
$offset = (int) $offset;
$query->bindParam(':limit', $limit, PDO::PARAM_INT);
$query->bindParam(':offset', $offset, PDO::PARAM_INT);
$query->execute();
$list = null;
foreach($query->fetchAll() as $wiki) {
$list[] = $wiki;
}
return $list;
}
return null;
}
生成的SQL是:
SELECT id, date, title FROM wiki WHERE ( lower(title) LIKE lower(:keyword0) )
AND ( lower(title) LIKE lower(:keyword1) )
ORDER BY update_date DESC LIMIT :offset,:limit;
我已检查过关键字,即&#34; dog&#34;和&#34; cat&#34;分别具有索引0和1,并注入:keyword0和:keyword1。