phpcodeignitermodel-view-controllerhtml-tableresultset

Display database search results as an HTML table with CodeIgniter


I am trying to create a search form in Codeigniter. I want to give the user 4 different options to search from. For the result I want a table that displays all 11 columns in the table I am searching from. This is the code I have so far.

Controller:

public function index()
{
    $this->searchTest();
}

public function searchTest()
{
    $this->load->model('reg_model');
   
    $search_term = array(
        'firstName' => $this->input->post('firstName'),
        'lastName' => $this->input->post('lastName'),
        'street' => $this->input->post('street'),
        'dob' => $this->input->post('dob')
    );

    $data['query'] = $this->reg_model->test($search_term);

    $this->load->view("reg_header");
    $this->load->view("reg_nav");
    $this->load->view("reg_search_form", $data);
    $this->load->view("reg_search", $data);
}

Model:

public function test($search_term = 'default')
{
    $this->db->select('*');
    $this->db->from('voterinfo');
    $this->db->like('firstName', $search_term);
    $this->db->or_like('lastName', $search_term);
    $this->db->or_like('street', $search_term);
    $this->db->or_like('dob', $search_term);
    $query = $this->db->get();
    return $query->result_array();
}

View:

<?php
$this->load->library('table');
foreach ($query as $row) {
    echo $this->table->generate($row);
}
?>

Solution

  • If you want to put in table using codeigniter table class , it should be something like this:

    $this->load->library('table');
    
    $this->table->set_heading(array('Name', 'Color', 'Size')); //your column name
    
    
    foreach($query as $row ){
       $this->table->add_row($row);
    }
    
    echo $this->table->generate(); 
    

    you need also to modify your model. You're query is wrong you forgot the key , it should be like this:

    public function test($search_term='default'){
    
    
    
       $this->db->select('*');
       $this->db->from('voterinfo');
       $this->db->like('firstName', $search_term['firstName']);
       $this->db->or_like('lastName', $search_term['lastName']);
       $this->db->or_like('street', $search_term['street']);
       $this->db->or_like('dob', $search_term['dob']);
       $query = $this->db->get();
    
    
       return $query->result_array();
    
    }