I am very new to CodeIgniter, which has been very hard for me to learn so far. I mostly never work with frameworks and this is my first time.
I understand MVC but I really don't know how to create a search, even just a basic one: I just want someone to send a word in an input and search it in my database (with Ajax or not) and give the answer back. Could anyone help me with some ideas for how I should proceed? I understand that in the view I will put my divs, inputs and more, and in the controller I will call my functions that will interact with my model. I'm struggling with how to integrate them on CI though because the view is actually filled via the controller and I believe I can't use the functions of from it in the view.
Any help please?
Start by creating a controller that will be handling the search requests and displaying the search page, followed by the search-term passed to the model for database lookup (and sending it back to the controller). The controller will pass it to the view.
A little example;
The Controller
class Search extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper('form');
$this->load->model('search_model');
}
public function index()
{
$this->load->view('search_form');
}
public function execute_search()
{
// Retrieve the posted search term.
$search_term = $this->input->post('search');
// Use a model to retrieve the results.
$data['results'] = $this->search_model->get_results($search_term);
// Pass the results to the view.
$this->load->view('search_results',$data);
}
}
The Model
class Search_model extends CI_Model {
public function get_results($search_term='default')
{
// Use the Active Record class for safer queries.
$this->db->select('*');
$this->db->from('members');
$this->db->like('username',$search_term);
// Execute the query.
$query = $this->db->get();
// Return the results.
return $query->result_array();
}
}
The view for displaying the search form
<?php
echo form_open('search/execute_search');
echo form_input(array('name'=>'search'));
echo form_submit('search_submit','Submit');
?>
The View for displaying results
<div>
<?php
// List up all results.
foreach ($results as $val)
{
echo $val['username'];
}
?>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With