2

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>";

?>
2
  • sorry this is a better link stackoverflow.com/questions/2476307/… Commented Jul 16, 2012 at 9:37
  • 2
    "Quick Quick please" is not a very nice way to ask volunteers for help. Commented Jul 16, 2012 at 9:37

5 Answers 5

10

Use DISTINCT in your query.

"SELECT DISTINCT year FROM data";
Sign up to request clarification or add additional context in comments.

Comments

4

just change Your query. is better

$sql = "SELECT distinct year FROM data";

Comments

2

Another technique:

select year from table group by year

Comments

1

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>";

Comments

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.