phpcodeigniteractiverecordsql-likequery-builder

CodeIgniter active record query with like() and or_like()


The problem is that it displays all the rows from db instead of displaying only those rows which contain search keywords.

public function search($data)
{

    $name = $data["name"];
    $surname = $data["surname"];

    $this->db->select('*');
    $this->db->from('workers');
    $this->db->like('name', '%' . $name . '%');
    $this->db->or_like('surname', '%' . $surname . '%');

    $query = $this->db->get();

Solution

  • You wrote CI like query wrong way.Look the documentation how to write it properly

    Your query should be like this.No need to add %. CI add them if you do not pass 3rd parameter of like function.

    $this->db->select('*');
    $this->db->from('workers');
    $this->db->like('name', $name);
    $this->db->or_like('surname', $surname);
    
    $query = $this->db->get();
    

    Better do with some valid data like this.

    $this->db->select('*');
    $this->db->from('workers');
    if($name)
    {
       $this->db->or_like('name', $name);
    }
    if($surname)
    {
        $this->db->or_like('surname', $surname);
    }
    $query = $this->db->get();