我正在尝试在Codeigniter中创建一个搜索表单。我创建了一个文本框,用户可以在其中输入他们想要搜索的书的标题和作者。到目前为止,这是我的代码,我的代码是对的还是不对?
控制器:
function searchBooks() {
$postlist['bookSearch'] = $this->view_book_model->getSearchBook($this->input->post('search'));
$this->load->view('searchbooks.php', $postlist);
}
型号:
function getSearchBook($searchBook) {
$select_query = "Select * from books where Title = '.$searchBook.' ";
$query = $this->db->query($select_query);
return $query->result();
}
视图:
<input type="text" class="searchBox" id="searchBox"> </input>
<input type="submit" value="Search" class="btnInput" id="btnInput"> </input>
<br><br>
<?php
echo '<hr>';
echo '<h3> Book List </h3>';
echo '<table id="maintable" class="table">';
echo '<th> Book ID</th>';
echo '<th> Book Title </th>';
echo '<th> Book Author </th>';
echo '<th> # of Copies </th>';
echo '<th> Available Copy </th>';
foreach($bookSearch as $rows) {
echo '<tr>
<td>'.$rows->BookID.'</td>
<td>'.$rows->Title.'</td>
<td>'.$rows->Author.'</td>
<td>'.$rows->Qty.'</td>
<td>'.$rows->OnHand.'</td>
</tr>';
}
echo '</table>';
?>
我使用ajax来检索用户在搜索框中输入的输入。问题是,我不知道如何在搜索用户搜索的书的标题和作者方面对我的模型进行编码。
如果您可以使用查询生成器会更好,这里是:
function getSearchBook($searchBook) {
if(empty($searchBook))
return array();
$result = $this->db->like('title', $searchBook)
->or_like('author', $searchBook)
->get('books');
return $result->result();
}
我认为您没有按确切的书名进行搜索。您应该在sql查询中使用like进行搜索。尝试更改sql查询
$select_query = "Select * from books where Title like '%$searchBook%' ";