ActiveRecord + CodeIgniter - Return single value from query, not in array form

29,387

Solution 1

$query = $this->db->get(); // your ActiveRecord query that will return a col called 'sum'

echo $query->row('sum');

Solution 2

$output = $this->db->query("YOUR QUERY")->row()->fieldname;

OR

$output = $this->db->get("TABLE NAME")->row()->fieldname;

Where fieldname is the name of the field you want the output of in your query.

Solution 3

this isn't the prettiest way. i can't find a way to do it with the active record api. but here's a one-liner to get it.

$result = array(

    array('sum' => '23')

);

echo current( current( $result ) );
Share:
29,387
txmail
Author by

txmail

Updated on May 10, 2020

Comments

  • txmail
    txmail about 4 years

    Say you construct an activerecord query that will always just return a single value, how do you just address that single value instead of getting an array in return? For instance I am using an ActiveRecord query to return the SUM of a single column, it will only return this one single SUM, instead of having to parse the array is there a way to assign the value as a function return equal to that value instead of getting an array?

  • txmail
    txmail about 14 years
    Wouldnt that set a value in an array?
  • njbair
    njbair about 14 years
    This is the right answer for Active Record, but in general if you wanted to store the first result of any array into a var you could use something like: $var = whatever(); $var = $var[0]; and then from that point on you don't have to mess with indices.