So I am working on a custom blog system where on each post I show the list of tags associated with that post. Next to each one of the the tags I want to show a count of how many other posts use each tag, and that is what I am having issue figuring out.
Here the the 3 tables I have one for the posts, tags, and then post_tags for assigning which posts have what tags.
mysql> DESC post;
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| id | mediumint(9) | NO | PRI | NULL | auto_increment |
| contents | longtext | NO | | NULL | |
+----------+--------------+------+-----+---------+----------------+
mysql> DESC tags;
+-------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+----------------+
| id | mediumint(9) | NO | PRI | NULL | auto_increment |
| tag | varchar(255) | NO | | NULL | |
+-------+--------------+------+-----+---------+----------------+
mysql> DESC post_tags;
+---------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+----------------+
| id | mediumint(9) | NO | PRI | NULL | auto_increment |
| post_id | mediumint(9) | NO | | NULL | |
| tag_id | mediumint(9) | NO | | NULL | |
+---------+--------------+------+-----+---------+----------------+
Here is the code I use to pull the list of tags for the post
$stmt = $con->prepare('SELECT * FROM tags LEFT JOIN post_tags ON post_tags.tag_id = tags.id JOIN post ON post.id = post_tags.post_id WHERE post.id = ?');
$stmt->bind_param('i', $_GET['id']);
$stmt->execute();
$tags = $stmt->get_result();
and how I display them
<?php while ($tag = $tags->fetch_assoc()) : ?>
<span class="tags"><a href="tags.php?<?= $tag['tag'] ?>" class="tag tag-35762 "><span class="name"><?= $tag['tag'] ?></span><span class="count">1</span></a>
<? endwhile ?>