Demos, Blog, PHP & MySQL, Tutorials

Blog Series


In the last tutorial we created the ability for having tags for each post, this part will continue and add the ability to collect a list of all tags and place them into a sidebar.

admin demo: https://daveismyname.blog/demos/simpleblog-tags/admin

username: demo
password: demo

This code will be written inside sidebar.php. First, create an array that will later store all the tags.

$tagsArray = [];

Next, collect all the tags from the posts table but to remove any case-insensitive or like for like duplicated we use DISTINCT and LOWER to get only unique matches that are all in lower case this stops Demo and demo being two different tags. 

$stmt = $db->query('select distinct LOWER(postTags) as postTags from blog_posts where postTags != "" group by postTags');

Now loop over the results breaking each tag into its own array key then loop over that to add each one to the $tagsArray.

while($row = $stmt->fetch()){
    $parts = explode(',', $row['postTags']);
    foreach ($parts as $tag) {
        $tagsArray[] = $tag;
    }
}

Now with a list of all the tags array_unique can be used to remove any duplicates:

$finalTags = array_unique($tagsArray);

Finally, this array list is looped over and the tags are displayed.

foreach ($finalTags as $tag) {
    echo "<li><a href='t-".$tag."'>".ucwords($tag)."</a></li>";
}

The full code block looks like this:

<h1>Tags</h1>
<hr />

<ul>
    <?php
    $tagsArray = [];
    $stmt = $db->query('select distinct LOWER(postTags) as postTags from blog_posts where postTags != "" group by postTags');
    while($row = $stmt->fetch()){
        $parts = explode(',', $row['postTags']);
        foreach ($parts as $tag) {
            $tagsArray[] = $tag;
        }
    }

    $finalTags = array_unique($tagsArray);
    foreach ($finalTags as $tag) {
        echo "<li><a href='t-".$tag."'>".ucwords($tag)."</a></li>";
    }
    ?>
</ul>