Search code examples
phpformsinputdql

PHP Dropdown pulling information from SQL database


I'm trying to create a drop down with all my currencies, at the moment the values are 1, 2 & 3. I need the values of the drop down to stay as the number, but want the option text to say GBP, EUR and USD instead. I have this code:

<select class='dc_input' name='currency' id ='currency'>
    <?php

    $sql="SELECT l.currency
                    FROM locations l
                    GROUP BY l.currency";

        $sites = mysql_query($sql);
        while ($row = mysql_fetch_assoc($sites)) {
            echo '<option value="' .$row['currency']. '"' .$selected. '>  </option>';
        }
    ?>

</select>

This works, I just don't know what to put in to make it change for each one.


Solution

  • <?php
    $currencies = array('', 'GBP', 'EUR', 'USD');
    ?>
    <select class='dc_input' name='currency' id ='currency'>
        <?php
    
        $sql="SELECT l.currency
                        FROM locations l
                        GROUP BY l.currency";
    
            $sites = mysql_query($sql);
            while ($row = mysql_fetch_assoc($sites)) {
                $index = $row['currency'];
                echo '<option value="' .$index. '"' .$selected. '> '.$currencies[$index].' </option>';
            }
        ?>
    
    </select>
    

    Also you can store currency ID's and currency name's on database . If you start supporting more than 3 currencies, it will be more easier for you.