Vishal
Vishal

Reputation: 31

How to search full name in codeigniter

My database table structure is as follows.

 -------------------------------
| id | f_name | m_name | l_name |
 -------------------------------

This is my model that I used to get results.

    public function getContactInfo($start,$perpage) //  Swapnil
    {
        $keyword= $this->input->get('keyword'); // vishal
    
        $this->db->like(array('colleges_fname'=>$keyword)); // vishal
        $this->db->limit($perpage,$start);
    
        $result = $this->db->get("colleges");
    
        if($result->num_rows()>0) {
            return $result->result();
        } else {
            return false;
        }
    }

This is my view.

<form class="form-inline ml-3" type="get" action="<?php echo base_url('clerk/collegestudent/view')?>">
    <div class="input-group input-group-sm ">
        <input class="form-control form-control-navbar" type="search" placeholder="Search" aria-label="Search" name="keyword">
        <div class="input-group-append">
            <button class="btn btn-navbar" type="submit">
                <i class="fas fa-search"></i>
            </button>
        </div>
    </div>
</form>

Currently it searches for the first name only. How to improve my code to search both first name and last name at a time?

Upvotes: 1

Views: 449

Answers (1)

marcogmonteiro
marcogmonteiro

Reputation: 2172

    public function getContactInfo($start,$perpage) //  Swapnil
    {
        $keyword= $this->input->get('keyword'); // vishal
        
        $this->db->group_start();
        $this->db->like('f_name', $keyword, 'after'); 
        $this->db->or_like('l_name', $keyword, 'after');
        $this->db->group_end();
        $this->db->limit($perpage,$start);
    
        $result = $this->db->get("colleges");
    
        if($result->num_rows()>0) {
            return $result->result();
        } else {
            return false;
        }
    }

The lines from group start to group end will reproduce something like:

(f_name LIKE "string%" OR l_name LIKE "string%")

If you want to search in both directions remove the third param in the like statements.

Upvotes: 2

Related Questions