Reputation: 89
I tried to make a search bar so users will be able to search products by searching on the product name but its not working and I'm not able to search a product.
This is my controller function:
<?php
class SearchController extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('Search_model');
}
public function index(){
$data = array();
}
function search_keyword(){
$keyword = $this->input->post('keyword');
$data['results'] = $this->Search_model->search($keyword);
//laad de view
$this->load->view('result_view',$data);
}
}
?>
This is my model function:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Search_model extends CI_Model {
function __construct(){
parent::__construct();
}
function search($keyword) {
$this->db->select('product_naam');
$this->db->like('product_naam',$keyword);
$query = $this->db->get('products');
return $query->result_array();
}
}
?>
And this is my view file with searchbar:
<?php include_once('templates/header.php'); ?>
<center>
<h2>Zoek een cadeau</h2><br>
<form class="navbar-form" role="search" action="<?php echo base_url(); ?>SearchController/search_keyword" method="POST">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" name="keyword" size="30px; ">
<div class="input-group-btn">
<button class="btn btn-default " type="submit" value = "Search"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
</center>
<div class="clearfix"></div>
<table>
<?php foreach($results as $row){ ?>
<tr>
<td><?php echo $row->product_naam?></td>
</tr>
<?php } ?>
</table>
<?php include_once('templates/footer.php'); ?>
I hope someone can help me with this problem!, thanks
Upvotes: 0
Views: 1165
Reputation: 2025
I don't think like() will help you much with your particular needs. Your best bet, I guess, would be to bypass the problem and use a where function containing your LIKE clause:
$this->db->select('product_naam')->from('products')
$this->db->where("product_naam LIKE '%$keyword%'")->get();
Or if you want pure ci you have to change your 'like' line :
$this->db->like('product_naam',$keyword);
For %$query you can use
$this->db->like('product_naam',$keyword,'before');
and for $query% you can use
$this->db->like('product_naam',$keyword,'after');
Upvotes: 1
Reputation: 26153
Because you use $query->result_array();
, items should be taken by
<td><?php echo $row['product_naam']?></td>
result_array()
This method returns the query result as a pure array, or an empty array when no result is produced
Upvotes: 1