dongzhangji4824 2016-08-07 22:28
浏览 38
已采纳

我应该从数据库中获取数据来创建下拉列表吗? [关闭]

I have a form with a dropdown selection whose option are determined from a table on a database. Periodically I will (manually) add more options to the dropdown and the database. Either I can make the dropdown selection get the options from the database like this:

<select class="form-control" name="category" id="category">

    <?php
    $sql = "SELECT id, category FROM categories;";
    $result = $GLOBALS['conn']->query($sql);
    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            $category = $row['category'];
            $id = $row['id'];
            echo "<option value='$id'>$category</option>";
        }
    }
    ?>
</select>

Which will give me less work because all I have to update now is the database and the form will update itself.

Or I can manually input the options into the form like this:

<select class="form-control" name="category" id="category">
    <option value='1'>option1</option>
    <option value='2'>option2</option>
    <option value='3'>option3</option>
</select>

This way will require more manual work but has the advantage of not having to connect to the database each time (less work for the servers).

My question is which method should I use? The method that gives me more work or the method that gives the server more work?

  • 写回答

1条回答 默认 最新

  • dougan0529 2016-08-07 22:37
    关注

    There are arguments pro and against using a database for select. As for the pro arguments, it is relatively easy to update - you just insert a new value and it will appear in your form. The problem with this approach is that your application will do a query each time that you render your form. In websites with millions of clicks this is not a good idea. So, the alternative used is that the query result is cached in some intermediary layer, especially when these values are not changing a lot. From my experience, the best way to handle these values is to load them from configuration files. These are values that rarely change and a new value can be added there. These can be still cached and a database hit is not required.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误