Dynamic Drop Down menus

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • RobAC
    Senior Member
    • Jan 2001
    • 1414
    • 3.8.x

    Dynamic Drop Down menus

    I've built a php/mysql -based dynamic dropdown menu with the following code:

    PHP Code:
    <SELECT>
          <?
          
    $db mysql_connect("localhost""smth""smth");
          
    mysql_select_db("database_name");
          
    $strSQL "SELECT * FROM select1options ORDER BY name";
          
    $rs mysql_query($strSQL);
          
    $nr mysql_num_rows($rs);
          for (
    $i=0$i<$nr$i++) {
          
    $r mysql_fetch_array($rs);
          echo 
    "<OPTION VALUE=\"".$r["name"]."\">".$r["name"]."</OPTION>";
          }
          
    ?>
          </SELECT>
    However, the problem is that it returns all the records in the option tags.

    For example if I'm building a dropdown menu on country, and there are three recordwith "USA" in the country field, it returns three options with the value of "USA". I only want it to return one for each unique value in the table.

    How do I do that?
    Rob
  • DoE
    Senior Member
    • Sep 2007
    • 763

    #2
    You can use DISTINCT, but it has to be on a column name, e.g.:

    SELECT DISTINCT country FROM ....

    DISTINCT is pretty slow though. What I would do as you are using the wild card to pull all data anyways is something like this:

    <SELECT>
    <?
    $temp_holder = array();

    @ $db = mysql_connect("localhost", "smth", "smth");
    mysql_select_db("database_name");
    $strSQL = "SELECT * FROM select1options ORDER BY name";
    $rs = mysql_query($strSQL);
    $nr = mysql_num_rows($rs);
    for ($i=0; $i<$nr; $i++) {
    $r = mysql_fetch_array($rs);

    if (!in_array($r['name'], $temp_holder))
    {
    $temp_holder[$i] = $r['name'];
    echo "<OPTION VALUE=\"".$r["name"]."\">".$r["name"]."</OPTION>";
    }

    }
    unset($temp_holder);
    ?>
    </SELECT>

    Comment

    widgetinstance 262 (Related Topics) skipped due to lack of content & hide_module_if_empty option.
    Working...