Demos, Blog, PHP & MySQL, Tutorials

Creating a blog from scratch with PHP - Part 8 Tags Sidebar

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://demos.daveismyname.blog/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>

 

David Carr

David Carr

For the past 12 years, I’ve been developing applications for the web using mostly PHP. I do this for a living and love what I do as every day there is something new and exciting to learn.

In my spare time, the web development community is a big part of my life. Whether managing online programming groups and blogs or attending a conference, I find keeping involved helps me stay up to date. This is also my chance to give back to the community that helped me get started, a place I am proud to be apart of.

Besides programming I love spending time with friends and family and can often be found together going out catching the latest movie, staying in playing games on the sofa or planning a trip to someplace I’ve never been before.