0

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.

Drew
  • 29,895
  • 7
  • 74
  • 104
user2701687
  • 327
  • 1
  • 5
  • 13
  • store the first result in a variable , and display it , when you are fetching it next time, before display compare it to the variable , if matches do nothing , else display and store – Satya Oct 05 '13 at 01:25
  • 1
    Also, see [Why shouldn't I use mysql_* functions in PHP?](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). – Boaz Oct 05 '13 at 01:26

2 Answers2

8

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.

Thomas Kelley
  • 10,187
  • 1
  • 36
  • 43
2

@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>
    ";
}
phpLearner
  • 197
  • 10
  • +1 for a PHP alternative. Although, instead of adding it to a comma-separated list of strings, it'd be more optimal to push the value into an array, and use `in_array()` to determine if it's already there. String comparisons can get expensive and inexact (for example, if the value already contained a comma). – Thomas Kelley Oct 05 '13 at 21:58
  • Good point @ThomasKelley. I am still a newbie. Learn something new today. – phpLearner Nov 29 '13 at 11:20