Welcome Guest, Not a member yet? Register   Sign In
Best way to do this...
#1

[eluser]Chris.Campbell[/eluser]
If I want to put the number of current comments inside my link to my blogs comments, is it to taxing on the database to look through each comment and count? What's the best way to do this.
#2

[eluser]xwero[/eluser]
If you don't want to do a 'select count(*)' sql you could add a count_comments field to your posts table which increases every time a comment is added.
#3

[eluser]Chris.Campbell[/eluser]
OK so if I add the field. How does it know every time a comment is added? I am new to PHP, having a tough time wrapping my head around relational databases.
#4

[eluser]Ryuuzaki92[/eluser]
you can get the post data and update it like this:
Code:
$query = $this->db->getwhere('posts', array('id' => $post_id));
$row = $query->row();
$row->count_comments++;
$this->db->update('posts', $row, array('id' => $post_id));

but i prefer using SQL for this simple task:
Code:
$this->db->query('UPDATE posts SET count_comments = count_comments + 1 WHERE id = ?', array($post_id));
#5

[eluser]xwero[/eluser]
You count when you process the adding of a comment
Code:
//model
function add_comment($post)
{
   $itemid = $post['blogid']; // the id of the blog post
   $this->db->query('UPDATE posts SET count_comments = count_comments + 1 WHERE id = ?', array($itemid));
   $this->db->update('comments',$post);
}
#6

[eluser]Chris.Campbell[/eluser]
Sorry if I am a little slow at this... this is what I have right now. There are no errors but it's not inserting any values into count_comments.

Code:
function comment_insert()
    {
        $this->db->insert("comments", $_POST);
        $this->db->query('UPDATE entries SET count_comments = count_comments + 1 WHERE id = ' . $_POST['entry_id']);
        
        redirect("blog/comments/" . $_POST['entry_id']);
    }
#7

[eluser]Ryuuzaki92[/eluser]
make sure you set the default value for count_comments as 0. anyways your code is very insecure. sql injection can happen. don't use $_POST, use $this->input->post() instead.
#8

[eluser]Chris.Campbell[/eluser]
I have the default to 0 and it's still not working Sad . And thanks! I realize it is insecure but I am coding just to learn the basics right now Smile
#9

[eluser]xwero[/eluser]
try to execute the sql statement in phpmyadmin and see what the result is.
#10

[eluser]Chris.Campbell[/eluser]
Ok I run this:
Code:
UPDATE entries SET count_comments = count_comments + 1 WHERE id = 2

And I get this:
Quote:Affected rows: 0 (Query took 0.0004 sec)




Theme © iAndrew 2016 - Forum software by © MyBB