简体   繁体   中英

Count total posts belonging to main category and subcategories in PHP MySQL

I need to count total number of posts belonging to a main category and its subcategories in PHP/MySQL. I have three tables given by:

tb_categories

在此处输入图片说明

tb_posts

在此处输入图片说明

tb_posts_to_categories

在此处输入图片说明

Now to get total number of posts belonging to a category and all its subcategories, I am using the following code:

<?php
include("includes/db-config.php");

// Create connection
$connection = @mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD, DATABASE_NAME) 
or die(mysqli_connect_error());

    // Get total number of posts in a category
    function get_post_counts($category_id)
    {
        global $connection;
        $category_to_post = array();

        // Build database query
        $sql = "SELECT COUNT(`post_id`) AS `post_count`, `category_id` FROM `tb_posts_to_categories`  GROUP BY `category_id`";

        // Execute database query
        $rs = mysqli_query($connection, $sql);
        while($row = mysqli_fetch_assoc($rs))
        {
            $category_to_post[$row['category_id']] = $row['post_count']; 
        }

        // Build database query
        $sql2 = "SELECT `category_id`, `category_parent` FROM `tb_categories` WHERE `category_parent` <> 0";

        // Execute database query
        $rs2 = mysqli_query($connection, $sql2);

        while($row2 = mysqli_fetch_assoc($rs2))
        {
            $category_to_post[$row2['category_parent']] += $category_to_post[$row2['category_id']]; 
        }

        return $category_to_post[$category_id];
    }

$total_posts = get_post_counts(2);

echo $total_posts;

?>

Output

11

But this output is not correct. It should be equal to 8. But if you supply subcategory id then output is correct. It only mess up when parent category id is supplied to the function.

Since I have one-to-many relationship. A post can be assigned to several categories and even to its subcategories. The posts associated to more than two categories (One main category and its subcategories) are calculated again which yields me result 11 instead of 8.

However the code works fine when a post is associated to two different parent categories or their any subcategories. The issue is only when a post is associated to a main category and its multiple subcategories. How can we fix such wrong calculation? Please help me on this guys. Thanks!

Try this to count posts in category and it's direct subcategories.

SELECT COUNT(DISTINCT post_id)
FROM (
  (SELECT post_id
  FROM tb_posts_to_categories
  WHERE category_id = 2)
  UNION ALL
  (SELECT pc.post_id
  FROM tb_posts_to_categories pc
    JOIN tb_categories c ON pc.category_id = c.category_id
  WHERE c.category_parent = 2)
) AS t

This is another, smaller variant :-) But MySQL sometimes gets stucked with indexes usage if WHERE contains OR condition.

SELECT COUNT(DISTINCT pc.post_id)
FROM tb_posts_to_categories pc
  JOIN tb_categories c ON pc.category_id = c.category_id
WHERE c.category_parent = 2 OR c.category_id = 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM