I understand you're only looking for a count - but the type of count you're looking for is a little more complicated than that. Not only do you want the count for pages in a category, but want to include the count in the pages beneath it. The link I gave you will make this request and most other tree-related queries a breeze.
Protato: Your code likely works, but you're running a loop and initiating a new query each time. What happens if the loops runs 100-200 queries per page load? You'd be using up a significant amount of resources, and it would become disastrous as more visitors came to the site. That's without including any other queries that are already on the page.
If the SQL query for this is possible, it's well above my head. You might be able to try something along these lines:
SELECT c1.cat_id, c1.parent_id, COUNT(c1.cat_id) AS count
FROM categories AS c1
LEFT JOIN categories AS c2
ON c2.parent_id = c1.cat_id
LEFT JOIN categories AS c3
ON c3.parent_id = c2.cat_id
LEFT JOIN categories AS c4
ON c4.parent_id = c3.cat_id
GROUP BY c1.parent_id, c1.cat_id WITH ROLLUP;
But you are going to need to do a lot of work in PHP to get your results. Some sort of recursive function with the use of if statements. You're also limited here to 4 levels - so if you have anything deeper than that, you're going to have to adjust the query.
That's why I recommended you take a look at that article if you really need this functionality.