populate drop down list from mysql database and don't repeat values
12,442
Solution 1
Use DISTINCT in your query.
"SELECT DISTINCT year FROM data";
Solution 2
Another technique:
select year from table group by year
Solution 3
in PHP side you have to do this
$all_data = array();
echo "<select name='year'>";
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
array_push($all_data,$row["column"]);
}
$all_data = array_unique($all_data);
foreach($all_data as $columns => $values){
print("<option value='$value'>$value</option>");
}
echo "</select>";
Solution 4
Here is a simple trick. Take a boolean array. Which value has not come in list print it in list and which value has come in list already once, set it as true through indexing the boolean array.
Set a condition, if boolean_array[ value ] is not true, then show value in list. Otherwise, don't.
mysql_connect('host', 'user', 'pass');
mysql_select_db ("database");
$sql = "SELECT year FROM data";
$result = mysql_query($sql);
echo "<select name='year'>";
while ($row = mysql_fetch_array($result)) {
if($bul[$row['year']] != true){
echo "<option value='" . $row['year'] . "'>" . $row['year'] . " </option>";
$bul[$row['year']] = true;
}
}
echo "</select>";
?>
Comments
-
Leo almost 2 years
I am populating a drop down menu from mysql database. It works well, But I want it not to repeat values. (i.e if some value is N times in database it comes only once in the drop down list)
Here is my code:
<?php mysql_connect('host', 'user', 'pass'); mysql_select_db ("database"); $sql = "SELECT year FROM data"; $result = mysql_query($sql); echo "<select name='year'>"; while ($row = mysql_fetch_array($result)) { echo "<option value='" . $row['year'] . "'>" . $row['year'] . "</option>"; } echo "</select>"; ?>