php Codeigniter 搜索框或搜索表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29098707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:14:21  来源:igfitidea点击:

Codeigniter Search box or search form

phpmysqlcodeigniter

提问by kathleen55

I am trying to create a search form in Codeigniter. I created a textbox where the user can input the title and author of the book they want to search. This is my code so far, is my code right or is it not?

我正在尝试在 Codeigniter 中创建一个搜索表单。我创建了一个文本框,用户可以在其中输入他们想要搜索的书名和作者。到目前为止,这是我的代码,我的代码对还是不对?

Controller:

控制器:

function searchBooks() {
    $postlist['bookSearch'] = $this->view_book_model->getSearchBook($this->input->post('search'));
    $this->load->view('searchbooks.php', $postlist);
}

Model:

模型:

function getSearchBook($searchBook) {
    $select_query = "Select * from books where Title = '.$searchBook.' ";
    $query = $this->db->query($select_query);
    return $query->result();
}

View:

看法:

<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>';
?>

I use ajax to retrieve the input entered by the user in the search box. The problem is that i don't know how to code my model in terms of searching for the title and author of the book searched by the user.

我使用 ajax 来检索用户在搜索框中输入的输入。问题是我不知道如何在搜索用户搜索的书名和作者方面对我的模型进行编码。

回答by JC Sama

It will be better if you could use the query builder, here:

如果您可以在此处使用查询构建器,那就更好

function getSearchBook($searchBook) {
    if(empty($searchBook))
       return array();

    $result = $this->db->like('title', $searchBook)
             ->or_like('author', $searchBook)
             ->get('books');

    return $result->result();
} 

回答by Lokesh Jain

I think you are not searching by exact book title. you should search with like in sql query. try to change in sql query

我认为您不是按确切的书名进行搜索。您应该在 sql 查询中使用 like 进行搜索。尝试更改 sql 查询

$select_query = "Select * from books where Title like '%$searchBook%' ";