PHP counting rows

Discussion in 'PHP' started by deleted-account, Jun 25, 2009.

  1. #1
    For my blogging system I want to have comments and there is going to be a string that displays how many comments are in the post.

    My tables are set up like so (just examples)

    post
    - id
    - title
    - cont

    comment
    - id
    - postid
    - cont

    Here is the code I am using to make sure to display the comments to their corresponding post.

    if ($postRow1['id'] = $commentRow['postid'])
    {
    echo $commentRow['cont'];
    }
    Code (markup):
    How do I count how many comments are in that specific post and then display the number of comments?
     
    deleted-account, Jun 25, 2009 IP
  2. dannywwww

    dannywwww Well-Known Member

    Messages:
    804
    Likes Received:
    18
    Best Answers:
    0
    Trophy Points:
    110
    #2
    $totalrows = mysql_num_rows(mysql_query("SELECT `id` FROM `comment` WHERE `postid` = '{$postRow1['id']}'"));
    // print out comments echo $totalrows;
    
    PHP:
    Something like that?
     
    dannywwww, Jun 25, 2009 IP
  3. Wrighty

    Wrighty Peon

    Messages:
    199
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Personally I would use:

    mysql_query("SELECT count(`ID`) as Total WHERE `postid` = '" . $postRow1['id'] . "'");

    However, I would also merge the query to get your entries with this one to make one query ... :)
     
    Wrighty, Jun 25, 2009 IP
  4. deleted-account

    deleted-account Active Member

    Messages:
    655
    Likes Received:
    19
    Best Answers:
    0
    Trophy Points:
    85
    #4
    Thanks for the help guys :)
     
    deleted-account, Jun 25, 2009 IP
  5. dweebsonduty

    dweebsonduty Active Member

    Messages:
    131
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    71
    Digital Goods:
    1
    #5
    I create a function to do this and just do something like

    $count = dbcount("SELECT * FROM table where field = thing");

    function dbcount($query)
    {
    $con = mysql_connect("#SERVER#","#USER#","#PASS#");
    
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
    
    mysql_select_db("#DBNAME#", $con);
    
    $result = mysql_query($query) or die(mysql_error());
    
    $num_rows = mysql_num_rows($result);
    
    mysql_close($con);
    return $num_rows;
    }
    PHP:
     
    dweebsonduty, Jun 27, 2009 IP