Reputation: 107
I have this code:
function search($terms){
$query = $this->db->get_where('products',"name LIKE '%$terms%' OR description LIKE '%$terms%'");
$product = $query->result_array();
foreach($product as $p):
$query2 = $this->db->get_where('categories', array('cat_id' => $p['prod_category']));
$category = $query2->row_array();
$product['category'] = $category['cat_link'];
endforeach;
return $product;
}
in my search function. It will return something like:
Array(
[0] => Array(
[prod_id] => 5
[prod_name] => Product
[prod_category] => 1
)
But what I'm after is:
Array(
[0] => Array(
[prod_id] => 5
[prod_name] => Product
[prod_category] => Category1
)
from the name of my category with the id 1. This is in my 'categories' table. The foreach loop is not the right way to accomplish this, but what is?
Upvotes: 1
Views: 15855
Reputation: 2008
You could simplify your search logic by letting your database handle the joining of your tables.
function search($terms){
$this->db->select('prod_id, prod_name, cat_name');
$this->db->from('products');
$this->db->join('categories', 'cat_id = prod_category', 'inner');
$this->db->like('name', $terms);
$this->db->or_like('description', $terms);
$query = $this->db->get();
return $query->result_array();
}
This is assuming your category name column is named cat_name
. The results would be as follow :
Array(
[0] => Array(
[prod_id] => 5
[prod_name] => Product
[cat_name] => Category1
)
Hope this helps!
Upvotes: 1
Reputation: 901
You can use below method:
I'm assuming that you've already loaded your libraries
CONTROLLER
function search()
{
$data['query'] = $this->Books_model->get_search();
$this->load->view(‘books’, $data);
}
MODEL
function get_search()
{
$match = $this->input->post(‘search’);
$this->db->like(‘bookname’,$match);
$this->db->or_like(‘author’,$match);
$this->db->or_like(‘characters’,$match);
$this->db->or_like(‘synopsis’,$match);
$query = $this->db->get(‘books’);
return $query->result();
}
VIEWS
<?=form_open(‘books/search’);?>
<?php $search = array(‘name’=>’search’,'id’=>’search’,'value’=>”,);?>
<?=form_input($search);?><input type=submit value=’Search’ /></p>
<?=form_close();?>
The result can be displayed using a HTML table
<table>
<tr><th>ID</th><th>Book</th><th>Author</th><th>Published</th><th>Price</th></tr>
<?php foreach($query as $item):?>
<tr>
<td><?= $item->id ?></td>
<td><?= $item->bookname ?></td>
<td><?= $item->author ?></td>
<td><?= $item->datepublished ?></td>
<td><?= $item->price ?></td>
</tr>
<?php endforeach;?>
</table>
This is what I'm using and I hope it'll help you to make search function on Code Igniter.
Upvotes: 1