douhan5853
2018-07-31 20:18
浏览 51
已采纳

从数据库中检索数据并将其存储在php中的select标记中

I'm working on update user account and my problem is how do i get the value of user type and store it in a combobox or select tag. Here's my code:

<select class="form-control" name="user_type" required>
   <option value=''>Select Type</option>
      <?php
        $query = "SELECT * FROM user_types";
        $result = mysqli_query($connections, $query);
        while($rows = mysqli_fetch_assoc($result)){
          $db_id = $rows["user_type_id"];
          $db_desc = $rows["description"];

          echo "<option value='$db_id'>$db_desc</option>";
       }
      ?>
</select>

From here i can get all of the user type in my database. Here's my user_types table.

enter image description here

And my users table

enter image description here

My question is how do i get the id and value of the user type based on users table and put that in select tag

enter image description here

Here's i can't get the value of user type

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douji9184 2018-07-31 20:29
    已采纳

    I'm thinking that you are working on editing users in your system. You would like to have the ability to change their User Type by allowing the logged in person to choose from a select box.

    I suggest the following:

    First you will need to read your User Types table into an array. The array keys need to be the user_type_id and the value needs to be the description.

    When you would show the user_type_id, instead show this new array value for that index.

    When you are displaying this field for editing, do exactly like your code in the original question but also denote the option as "selected" if it matches the user type of the user that you are editing.

    <?php 
    //$user will have all the data for the user you are editing
    $query = "SELECT * FROM user_types";
    $result = mysqli_query($connections, $query);
    $user_types = array();
    while($rows = mysqli_fetch_assoc($result)){
      $db_id = $rows["user_type_id"];
      $db_desc = $rows["description"];
      $user_types[$db_id] = $db_desc;
    }
    
    
    ?>
    <select class="form-control" name="user_type" required>
       <option value=''>Select Type</option>
          <?php
    
            foreach($user_types as $id => $desc){
              if ($user['user_type_id'] == $id){
                echo "<option selected='selected' value='$id'>$desc</option>";
              }else{
                echo "<option value='$id'>$desc</option>";
              }
           }
          ?>
    </select>
    

    When you handle the form being submitted, the value in $_POST['user_type'] will be the user_type_id corresponding to the selected user type.

    点赞 评论

相关推荐 更多相似问题