【问题标题】:PHP Dropdown pulling information from SQL databasePHP Dropdown 从 SQL 数据库中提取信息
【发布时间】:2013-07-29 14:40:00
【问题描述】:

我正在尝试使用我的所有货币创建一个下拉列表,目前的值为 1、2 和 3。我需要下拉列表的值保持为数字,但希望选项文本显示取而代之的是英镑、欧元和美元。我有这个代码:

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

这行得通,我只是不知道要为每个人添加什么。

【问题讨论】:

  • what to put in to make it change for each one. 是什么意思?
  • 表格中有文字吗?如果是,字段名称是什么?
  • 不,我在表格中没有文本,只有数字,我想在代码中定义文本。
  • 所以看看@Eray 的回答。他根据您提供的值定义了一个数组。

标签: php forms input dql


【解决方案1】:

您没有从数据库中选择号码。完成后,将文本放在开始/结束标记之间,并将数值留在 value 属性中。

echo '<option value="', htmlspecialchars($row['id']), '">',
     htmlspecialchars($row['currency']), '</option>';

【讨论】:

  • $row['currency'] 始终等于 1,2 或 3。我需要将其保留为值,并且文本需要根据数字进行更改。因此,如果它等于 1,则文本应为 GBP 等。
  • 没有包含文本的字段
  • @CarlaDessi,向您的项目添加一个数组,其中包含货币到价值的映射。然后使用$currencyMap[$row['currency']]之类的东西。
【解决方案2】:
<?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>

您还可以在数据库中存储货币 ID 和货币名称。如果您开始支持 3 种以上的货币,对您来说会更容易。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多