CodeIgniter Query with Single Result/Single Row

I’ve been asked this question more than once, so I decided to post it just in the case it can help some one out.

There are many occasions where you have a method that does a single row database query through CodeIgniter and just needs to return a single scalar value.

This is how I’ve seen it done before:

function getPhone(){
   $CI =& get_instance();
   $query = $CI->db->query("YOUR QUERY");
    foreach ($query->result() as $row) {
        $phone = $row->phone;
   }
   return $phone;
}

The following example shows how to do the same without the iteration:

function getPhone(){
    $CI =& get_instance();
    return $CI->db->query("YOUR QUERY")->row()->phone;
}

This example shows the sheer simplicity in using the CodeIgniter query method with a single result.

~ by ityndall on November 4, 2010.

One Response to “CodeIgniter Query with Single Result/Single Row”

  1. Thanks. That was nice n clear

Leave a Reply