In this tutorial, we will learn about CodeIgniter database select operation. CodeIgniter provides two methodologies by which we can select data from the database. Either we can use “query” method or active record methods.

In the following code, we are using the query method to get all records from the user table.

$query = $this->db->query("Select * from user");

Now all the available data will be stored with in the “$query” variable. To fetch all the record from the variable we have to call the result method. As you can observe in the follows code.


Active Record Select() & get()

We can also use the active record to optimize the line of code. Codeigniter providers select the method by which we can select the data within the database and by get method we can extract that selected data from the database. In the following code, you can observe we are selecting username and ID from the user table by the active record.

$query = $this->db->select('id, username')->get('user');

$id= $query->result()[0]->id;
$username = $query->result()[0]->username;

In the above code, you can observe we are extracting data from query variable and treated that as an array. Because maybe the above query will return more than one record and that will become an array. We are only fetching the username and ID of the first record from the returned query data.

Active Record Where Clause

Codeigniter provide as a separate method to filter the data by where clause. We can use their method separately or instead of that, we can use the get_where method. In the following example, we are going to illustrate the identical queries which will work alike.

$query = $this->db->get_where('user', array('id' => 1));

$query = $this->db->where('id', 1)->get('user');

So from the above query, you can observe that it is all about the logic. Even that you can create your own training methods by using active records or even that you can use conventional SQL Query within the query method to perform database operations in CodeIgniter.