0
votes

Hi I have tags in my database in a row called tags. They are separated by commas.

For example, they are stored in the database as tag1,tag2,tag3.

I want to retrieve them from the database and display them one by one separately and before displaying each tag, I want to link it to a URL.

Here's what I am doing so far,

$keywords = strip_tags($blog_query_results['keywords']); //Retrives the tags from the database

echo wordwrap(stripslashes($keywords), 65, "<br>",true); // this prints tag1,tag2, and so on.

While printing them I want to link tag1, tag2, and tag3 to different URLS.

2
You shouldn't store comma separated values in 1 field. What may seem like a quick solution at first, will bite you again and again because the data isn't normalised. Upgrade tags to their own table and join them on an id of the original table, it will make all kinds of things a lot easier later on. - Wrikken
@Wrikken: +1. I hope for everybody to learn this in time, I've made that mistake once... - The Pellmeister

2 Answers

2
votes

If you have a string like this :

$tags = 'tag1,tag2,tag3';

You can use the explode() function to get an array of tags :

$arr = explode(',', $tags);

And, then, just iterate over that array, to build a link for each item -- typically, using foreach() :

foreach ($arr as $t) {
    echo '<a href="...">' . htmlspecialchars($t, ENT_COMPAT, 'UTF-8') . '</a><br />';
}


As a sidenote : your database's design is probably a bit wrong, if you store more than one information in a single field.

If you have 3 tags for a post, you should have 3 rows (one per tag), either :

  • In the tags table,
  • Or in a join-table between your posts and tags tables.
0
votes

You can do:

$tags = explode(',', $keywords);
foreach($tags as $tag)
{
    echo "<a href='...' >$tag</a>";
}

etc...