Counting items in table via native count function fails? |
[eluser]nagata[/eluser]
So I have a forum on my website, all works fine except post counter code, this code for some reason keeps returning 1... Code: function count_user_posts($id) Code: $user = $this->access->get_user(); and for some reason it dosent change, I made test acc with NO posts made yet, and it still was showing 1 post... also this is access bit that returns the code: Code: function get_user()
[eluser]InsiteFX[/eluser]
Code: $this->db->count_all(); CodeIgniter Users Guide - Query Helper Functions
[eluser]nagata[/eluser]
Code: function count_user_posts($id) atleast something changed.... now it dosent see them XD
[eluser]InsiteFX[/eluser]
Your missing your Code: $query = $this->db->get('table_name');
[eluser]nagata[/eluser]
your code didnt help but gave an idea of how to do it, so I wrote this, it output exectly what i wanted, user post count so if anyone ever would need help with counting total posts, here ya go. Code: function count_user_posts($id)
[eluser]vitoco[/eluser]
(I'm not trying to be a dick about it ) Sometimes getting the desire result isn't enough, especially in apps constantly querying databases. Some pointers : - get ONLY what you need - try to avoid getting what you don't need From your code, you need only the NUMBER of rows that match your criteria, in this case with the id_user = $id, so by doing this : Code: $this->db->where('user_id', $id); 1.- you're getting all fields, because there's an implicit "SELECT *", i guess that includes some text fields. 2.- you're getting all records with user_id , that can be slow and doesn't make much sense. 3.- after that you count the records ( maybe a pre-calculated value, but i think that maybe with some iterations ). That's not right. Instead, use a simple BUILT-IN function ( that most RDBMS support ) "COUNT(*|field)" that returns an INT , also, try to especify the field because there are some exceptions counting NULL values. Code: $this->db->select('COUNT( user_id ) AS number'); Hope it helps. Saludos |
Welcome Guest, Not a member yet? Register Sign In |