kathleen55
kathleen55

Reputation: 341

Codeigniter Search box or search form

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?

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.

Upvotes: 1

Views: 33105

Answers (2)

Lokesh Jain
Lokesh Jain

Reputation: 579

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

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

Upvotes: 0

JC Sama
JC Sama

Reputation: 2204

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();
} 

Upvotes: 4

Related Questions