Welcome Guest, Not a member yet? Register   Sign In
Returning Single Value from a Query
#1

[eluser]Unknown[/eluser]
I want to return just a single value from a COUNT query. Is the below code the shortest way to do that? Seems like there should be more of a shortcut.

Code:
$query = $this->db->query('SELECT COUNT(*) FROM users');
$row = $query->row_array();
$count = $row[0];

If there is no shortcut to the above, how can I extend the Database class to create a new method to accomplish this?
#2

[eluser]stuffradio[/eluser]
Why are you doing it that way?

Code:
$query = $this->db->get('users');
return $query->num_rows();
#3

[eluser]Hannes Nevalainen[/eluser]
Code:
//Return the number of rows in $table_name.

$count = $this->db->count_all($table_name);

//More "complex" COUNT()'s can be done with $this->db->count_all_results();

$this->db->start_cache();
$this->db->select(array(
  'id',
  'header',
  'body'
));
$this->db->where('user_id',$user_id);
$this->db->stop_cache();

//Uses the active record query to count all rows.
$myPostsCount = $this->db->count_all_results('posts');

$myPosts = $this->db->get('posts')->result();
$this->db->flush_cache();

Details kan be found here-> Active Record - User Guide.

Hope this helps

//Hannes
#4

[eluser]stuffradio[/eluser]
He asked for a simple, short way of doing it. Not a long way of doing it Big Grin
#5

[eluser]Unknown[/eluser]
Thanks for both examples. Actually, I wasn't specifically looking at the COUNT function necessarily, but just the quickest way to return a single value from a query. Here is another example query.

Code:
$query = $this->db->query('SELECT SUM(points) FROM users');
$row = $query->row_array();
$sum = array_shift($row);

It would be great to just have a method like this:

Code:
$sum = $this->db->query_value('SELECT SUM(points) FROM users');

Anyway, after looking around, it seems that the DB class cannot be extended, but I'll have to create a model for this kind of thing.




Theme © iAndrew 2016 - Forum software by © MyBB