Reputation: 82
I want to display blog posts' tags as separate words inside my HTML. I have written the code but it just display all tags without separating them. i also want that no tag should repeat. here is code
$query = "select tags FROM blog";
$q_result = mysql_query($query) or die (mysql_error());
if(mysql_num_rows($q_result) != 0)
{
while($rr = mysql_fetch_row($q_result))
{
?>
<li><a href="blog_l?tags=<?php echo $rr[0]; ?>"><i class="fa fa-tags"></i><?php echo $rr[0]; ?></a></li>
<?php }} ?>
here is a screenshot that what I got:
What I want is to separate each keyword. Take a look at the first line, it's coming from a single post (saleem, finance, poetry, testing); I want to make them separate and DISTINCT so that no keyword will be repeated.
Upvotes: 2
Views: 170
Reputation: 72299
First suggestion :- mysql_*
is deprecated library so use now mysqli_*
or PDO
.
This will be the final code for you:-
<?php
$query = "select DISTINCT(tags) from blog"; // query to select unique tags
$q_result = mysql_query($query) or die (mysql_error());
$tag_data = array(); // create an empty array
if(mysql_num_rows($q_result) != 0){
while($rr = mysql_fetch_assoc($q_result)){ // fetch assoc instead of row
$tag_data[] = $rr['tags']; // assign tags to new array
}
}
foreach($tag_data as $tag){ // iterate through the tags array ?>
<li><a href="blog_l?tags=<?php echo $tag; ?>"><i class="fa fa-tags"></i><?php echo $tag; ?></a></li>
<?php }?>
Note:- you can directly do the printing part of the value in while loop. Thanks.In my code $tag_data
will be available for future use also.
Upvotes: 2
Reputation: 1428
After get result from database query, use the bellow code to get array of tag as you wish
$dbResult = $rr[0]; //"news, demo text"
$arrayTag = array_unique(array_map('trim', explode(",",$dbResult))); //['news', 'demo text']
Upvotes: 1