Question

So here's my php code:

$sql1 = "SELECT year FROM reports ORDER BY year DESC";
$res1 = mysql_query($sql1);
while($row = mysql_fetch_array($res1)) {
    $selectYear = "
        <select id='select_year'>
            <option value='".$row['year']."'>".$row['year']."</option>
        </select>
    ";
}

What I want it to do is just output one year instead of what its doing now which is outputting every single year and there is one entry for each month of the year so there are 12 entries with the same year so my html is this:

<select id='select_year'>
    <option value='2013'>2013</option>
    <option value='2013'>2013</option>
    <option value='2013'>2013</option>
    <option value='2013'>2013</option>
    <option value='2012'>2012</option>
</select>

But this is what I actually want:

<select id='select_year'>
    <option value='2013'>2013</option>
    <option value='2012'>2012</option>
</select>

This is to sort through all the results by year so that the user can just use the select to select which year they want to view.

Was it helpful?

Solution

There are lots of ways of doing this, but the easiest is probably:

$sql1 = "SELECT DISTINCT year FROM reports ORDER BY year DESC";

With DISTINCT, the database will only return one of each value. Then you don't have to waste any resources processing data on the PHP side.

OTHER TIPS

@Thomas Kelley has given the perfect answer above.

However, if you insist on PHP solution. You can do it as follows.

$res1 = mysql_query($sql1);
$placeHolder = ",";
while($row = mysql_fetch_array($res1)) {
    if ( strpos($placeHolder , $row['year']) )
        continue;
    $placeHolder .= $row['year'] .',';
    $selectYear = "
        <select id='select_year'>
            <option value='".$row['year']."'>".$row['year']."</option>
        </select>
    ";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top