I'm trying to find the most used categories in an intermediary table which contains two ids, I'm running this to find all the counts of posts against categories.
$data = $conn->query('SELECT * FROM category WHERE category_name ORDER BY category_name');
foreach($data as $row) {
$sql = "SELECT COUNT(p_id) FROM p_categories c,category ca WHERE c.category_id = ca.category_id AND category_name = :category_name";
$q = $conn->prepare($sql);
$q->execute(array(':category_name' => $row['category_name']));
$catco = $q->fetch();
echo '<p>'.$row['category_name'].' ('.$catco[0].')</p>';
}
This returns all the categories, but I want to limit it to only the top four categories having most p_id. I tried limiting the count query to 4 but that didn't work.
Here are the tables:
posts: p_id, p_name
p_categories: p_id, category_id
category: category_id, category_name