我继续收到此错误并且不明白错误。当用户搜索字符串时,它应该返回包含该字符串的所有消息。
这是我的搜索控制器:
public function doSearch() {
$this->load->model('Messages_model');
$string = $this->input->get('string');
$data['messages']=$this->Messages_model->searchMessages($string);
$this->load->view('view_messages', $data);
}
我在message_mdoel中的doSearch功能:
public function searchMessages($string) {
$sql = "SELECT * FROM Messages WHERE text LIKE '%string%' ORDER BY posted_at DESC";
$query = $this->db->query($sql,$string);
if($query->num_rows() > 0) {
$messages = array();
return $query;
}
}
和我的view_messages:
<?php foreach ($messages->result() as $message): ?>
<tr>
<td><?php echo $message->posted_at; ?></td>
<td><?php echo $message->user_username; ?></td>
<td><?php echo $message->text; ?></td>
</tr>
<?php endforeach; ?>
请帮助,谢谢
答案 0 :(得分:1)
更正您的SQL查询,您的查询如下:
$sql = "SELECT * FROM Messages WHERE text LIKE '%string%' ORDER BY posted_at DESC";
您使用了LIKE '%string%'
,但这是错误的。
应该是
$sql = "SELECT * FROM Messages WHERE text LIKE '%$string%' ORDER BY posted_at DESC";
并删除$string
中的$query = $this->db->query($sql,$string);
变量,如下所示:
$query = $this->db->query($sql);
更多详细信息CI query
文档http://www.codeigniter.com/userguide3/database/results.html
因此,模型中的最终searchMessages($string)
函数:
<?php
public function searchMessages($string) {
$sql = "SELECT * FROM Messages WHERE text LIKE '%$string%' ORDER BY posted_at DESC";
$query = $this->db->query($sql);
if($query->num_rows() > 0) {
//$messages = array();
return $query;
}
}
?>
或使用查询构建器类:
<?php
public function searchMessages($string) {
//$sql = "SELECT * FROM Messages WHERE text LIKE '%$string%' ORDER BY posted_at DESC";
$this->db->select('*');
$this->db->from('Messages');
$this->db->like('text', $string);
$this->db->order_by('posted_at', 'DESC');
$query = $this->db->get();
if($query->num_rows() > 0) {
return $query;
}
}
?>