简体   繁体   中英

How to prevent echoing same value twice in php

So I have this drop down list in my form which pull "tags" from database as value for drop down options:

<select name="cartags">
   <?php $result = mysql_query("SELECT * FROM Products WHERE ID > '0'");
   while($row = mysql_fetch_array($result))
   {
      echo "<option value=\""; echo $row['Tag']; echo "\""; echo ">"; echo $row['Tag']; echo "</option>";
   } 
   ?>   
</select>

What is my problem? My problem is that I am adding a lot of products into my databas and my code make dropdown list with tags for all this producst even if they have same tag. So what I need is solution how to prevent that same tag appear twice in my drop down.

I am pretty new to PHP and this is my first question here so I really hope that I explained my problem well.

Thanks in advance!

What is the purpose of WHERE ID > '0' ? If ID is an auto-increment then it will always be positive. If not, it should be.

Why are you using mysql_fetch_array and then only using the associative keys? You should use mysql_fetch_assoc instead.

Why are you using a new echo every time you want to output a variable? Just concatenate.

Why are you setting the same string in value as the option's text? Without a value, it defaults to the text anyway.

Why are you not using backticks around your column and table names?

Try this instead:

<select name="cartags">
<?php
  $result = mysql_query("SELECT DISTINCT `Tag` FROM `Products`");
  while(list($tag) = mysql_fetch_row($result)) {
      echo "<option>".$tag."</option>";
  }
?>
</select>

Try this

<select name="cartags">
<?php $result = mysql_query("SELECT Tag, COUNT(Tag) tg Products WHERE ID > '0'  GROUP BY Tag HAVING COUNT(Tag)>0 ORDER BY tg DESC");
while($row = mysql_fetch_array($result))
{
   echo "<option value=\""; echo $row['tg']; echo "\""; echo ">"; echo $row['tg']; echo " </option>";
 } 
?>   
</select>

It will also display the top tags that have the most first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM