phpmysqlcodeigniteractiverecordwhere-clause

How to add a WHERE clause to a CodeIgniter active record query?


I have my model set like this, so that it gets all the data from the table "tests" in the previously specified database:

class Get_db extends CI_Model {

    public function getData()
    {
        $query = $this->db->get("tests");
        
        return $query->result();
    }
}

and after I loaded all this data in my controller, and passed it to my view, I got this function in my view:

foreach ($records as $rec) {
    echo $rec->id . "  " . $rec->name . "   ";
}

and all the ids and names in my database will be posted where i want.

But what if I wanted to be more selective. Let's say that I've got a column in my database called "color" some of my rows will have color set to (for example) red, and some others to blue.

How can I display in my view just the rows with color=red? Or, more exactly, how can I tell PHP to get the data just of the rows that have color=red?


Solution

  • CodeIgniter uses an ActiveRecord library, be sure to read the documentation as it is clearly stated there.

    You can use $this->db->get_where() to filter on a WHERE clause. In your case:

    $query = $this->db->get_where('tests', array('color' => 'red'));