'Count and display only unique values of particular columns?

Basically, I have the following code and table setup. (It's a video upload system I'm making for fun). I have a page to display JUST tags for the videos, and then you should be able to click on a tag and it will search for any videos with the tag you clicked on, or multiple.

The issue I am having: my database is setup like this (for the parts that are relevant:) columns: tag1, tag2, tag3, tag4 rows: each row has the video information PLUS the values (if any, could be NULL if user chose no t to set a tag(s)) of tag1, tag2, tag3, and tag4.

There is GOING to be duplicates. There may be a tag in the row for "video1" with the value of "cat" in tag1 (col), but there could also be a tag in the row for "video2" with the value of "cat" in tag3 (col).

When I run my SQL query currently, the code for that shown below, if there are duplicates between the columns, it will display that duplicate tag twice in the list of tags. Now, in my SQL query, I can ignore/remove duplicate tags from a single column using the DISTINCT function (let's say the column of tag1 has 5 different rows with the value of "cat", I can ignore it and get it to just display/use that value once).

The end result I'm looking for:

-- Take ANY/ALL UNIQUE results between columns tag1, tag2, tag3, tag4 with ZERO duplicates DISPLAYED on the page, but behind each unique tag that IS displayed, I want a count of how many times that value shows up between all the tag columns in all rows. Like this for example:

cats: 5 dogs: 8 birds: 2 (etc)

The code below currently gives me the result displayed on the page of (p.s. Don't mind the odd named tags. I was just testing things earlier when uploading the videos that are currently in the site):

cats test idk test test kitty cat cats oil change kitty cats kitty testing bearded dragon test

Picture of database table is also included. Database Table

CODE:

<div class="tags-list">
<?php
$sql = "SELECT DISTINCT tag1, tag2, tag3, tag4 FROM videos;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    // Output of each row:
    while ($row = $result->fetch_assoc()) {

        // Define $row variables
        $tag1 = $row['tag1'];
        $tag2 = $row['tag2'];
        $tag3 = $row['tag3'];
        $tag4 = $row['tag4'];

        echo
        "<div class='list'>
            <a class='tags'>$tag1</a>
        </div>
        <div class='list'>
            <a class='tags'>$tag2</a>
        </div>
        <div class='list'>
            <a class='tags'>$tag3</a>
        </div>
        <div class='list'>
            <a class='tags'>$tag4</a>
        </div>
        ";
    }
} else {
    echo "No tags found :(";
    }

?>
</div>


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source