Welcome Guest, Not a member yet? Register   Sign In
Database Search Code Feedback
#1

[eluser]brian88[/eluser]
This is my first attempt at testing a search feature for a website. Its very simple and Im looking for feedback to make the search more usable without a ton of advance code. The code is simple now, Im just looking for some simple feedback to make the search a little better.

Table: blog
----------------------------------------------------
| id | title | body |
----------------------------------------------------
| 1 | How to lose weight fast | a bunch of lorum ipsom text |
----------------------------------------------------
| 2 | How to hack stuff | a bunch of lorum ipsom text again |
-----------------------------------------------------
| 3 | Top 10 best foods | lots of body copy about foods |
-----------------------------------------------------

model
Code:
// get search results
function search($keyword = '') {
  $q = $this->db->query("
   select *
   from blog
   where title
   like '%{$keyword}%'
   or body
   like '%{$keyword}%'
  ");
  
  if($q->num_rows() > 0){
   return $q->result();
  }
} // end function

controller
Code:
function search(){
     // get results from database for the users keyword
     $data['results'] = $this->main_mod->search( $this->input->post('search') );

     // views
     $this->load->view('homepage', $data);
} // end search

view
Code:
<div id='content'>

   &lt;form action="&lt;?php echo base_url('main/search'); ?&gt;" method="post" accept-charset="utf-8"&gt;
    
    &lt;input id='search' type="text" name="search" value="search"&gt;
    &lt;input type="submit" name="submit" value="search"&gt;
   &lt;/form&gt;

   <ul>
    &lt;?php if(!empty($results)): ?&gt; // if there are results

    &lt;?php foreach($results as $r): ?&gt;
    <li>
     <a href="#">&lt;?php echo $r->title; ?&gt;</a><br/> // blog title
     &lt;?php echo $r->body; ?&gt; // blog body text
    </li>
    &lt;?php endforeach; ?&gt;

    &lt;?php else: ?&gt;

    <p><br />no results</p>

    &lt;?php endif; ?&gt;
   </ul>
  } ?&gt;

</div>&lt;!-- #Content --&gt;
#2

[eluser]vitoco[/eluser]
better in which way ??, i you want to find multiple keywords in a field, google FULLTEXT SEARCH in mysql ( i guess that's your RDBMS ).

Saludos
#3

[eluser]brian88[/eluser]
thanks. i found a tutorial on full text search. a query like this is better. thanks

Is there a way to use the '%{$keyword}%' like in my first post with full text search?

When i type in "apples" i want it to find "apple" too

Code:
SELECT *, MATCH(title, body) AGAINST ('{$keyword}' IN BOOLEAN MODE) AS score
   FROM products
   WHERE MATCH(title, body)
   AGAINST('+{$keyword}' IN BOOLEAN MODE)
   ORDER BY score DESC




Theme © iAndrew 2016 - Forum software by © MyBB