CodeIgniter Forums
Displaying Average - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived General Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=21)
+--- Thread: Displaying Average (/showthread.php?tid=22660)



Displaying Average - El Forum - 09-16-2009

[eluser]PHP Creative[/eluser]
Very, very basic question I apologise. How do you display the AVG from a query as a variable? For example

Code:
$this->db->select_avg('age');
$query = $this->db->get('users');

Thanks a million.


Displaying Average - El Forum - 09-16-2009

[eluser]jedd[/eluser]
Code:
$this->db->select_avg('age');
$query = $this->db->get('users');

if ($query->num_rows() > 0)   {
   $row = $query->row();
   $average = $row->avg;
   }

If you're on PHP5 you can chain the query->row()->avg I believe. (Don't quote me - I don't use AR calls)


Displaying Average - El Forum - 09-16-2009

[eluser]Dam1an[/eluser]
There's a handy second paramter (it's in the user guide)

Quote:Writes a "SELECT AVG(field)" portion for your query. As with select_max(), You can optionally include a second parameter to rename the resulting field.