简体   繁体   English

如何将从数据库获取的选项添加到 select php 的末尾

[英]How to add option fetched from the database to the end in select php

I have a categories table where I have different categories.我有一个类别表,其中有不同的类别。 I have also add Other in the category.我还在类别中添加了其他。 When I'm getting the categories to populate the select I want the other option to appear at last.当我获得要填充 select 的类别时,我希望最后出现另一个选项。 how can I do that?我怎样才能做到这一点?

<select name="category" id="category" class="form-control <?php if (isset($errors['category'])) echo 'form-error'; ?>">
    <option value="">Select a category...</option>
    <?php while ($category = mysqli_fetch_assoc($categories)) { ?>
        <option value="<?php echo h($category['id']); ?>" <?php if (isset($_POST['category']) && h($category['id']) === $_POST['category']) echo 'selected'; ?>><?php echo h($category['name']); ?></option>
    <?php } ?>
</select>

If the Id of Other category is fixed, then you have to ignore it in your database query.如果其他类别的 Id 是固定的,那么您必须在数据库查询中忽略它。

Let's say that the Id of that option is 1, our query will be like this:假设该选项的 ID 为 1,我们的查询将是这样的:

select * from categories where Id <> 1

This query brings all categories except "other".此查询带来除“其他”之外的所有类别。

After that do the following:之后执行以下操作:

<select name="category" id="category" class="form-control <?php if (isset($errors['category'])) echo 'form-error'; ?>">
     <option value="">Select a category...</option>
     <?php while ($category = 
     mysqli_fetch_assoc($categories)) { ?>
    <option value="<?php echo h($category['id']); ?>" <?php 
      if (isset($_POST['category']) && h($category['id']) === 
       $_POST['category']) echo 'selected'; ?>><?php echo 
       h($category['name']); ?></option>
    <?php } ?>
     <option value="1">Other</option>
      </select>

hope it helps希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM