Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

populate drop down list from mysql database and don't repeat values

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

?>
like image 720
Leo Avatar asked Dec 01 '25 05:12

Leo


2 Answers

Use DISTINCT in your query.

"SELECT DISTINCT year FROM data";
like image 110
Rikesh Avatar answered Dec 02 '25 18:12

Rikesh


just change Your query. is better

$sql = "SELECT distinct year FROM data";


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!