douzi8112 2015-07-23 15:26
浏览 45
已采纳

php html。 如何在<option>中显示用户存储的db值? [关闭]

This will be shown on the user settings page.

(example)

       <select>
          <option value="0">0</option>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
          <option value="4">4</option>

       </select> 

If the user has value 3 stored in the db then i want the option-dropdown to show value 3 when the user is on the settings page. How can i do that?

  • 写回答

2条回答 默认 最新

  • ds3016 2015-07-23 15:33
    关注

    First, you need to get that value from the database. I'll use MySQLi in this example.

    <?php
        // Connecting to the database
        $mysqli = new mysqli($mysql_hostname, $mysql_username, $mysql_password, $mysql_dbname);
        if ($mysqli->connect_errno) {
            echo "Failed to connect to MySQL: (".$mysqli->connect_errno.") ".$mysqli->connect_error;
        }
        $mysqli->set_charset("utf8");
    
        $result = $mysqli->query("SELECT * FROM users");
    
        // Getting the row
        while ($row = $result->fetch_assoc()) {
            $valueFromDB = $row['columName'];
        }
    ?>
    
    <select>
        <option value="0" <?php if ($valueFromDB == "0") {echo " selected";} ?>>0</option>
        <option value="1" <?php if ($valueFromDB == "1") {echo " selected";} ?>>1</option>
        <option value="2" <?php if ($valueFromDB == "2") {echo " selected";} ?>>2</option>
        <option value="3" <?php if ($valueFromDB == "3") {echo " selected";} ?>>3</option>
        <option value="4" <?php if ($valueFromDB == "4") {echo " selected";} ?>>4</option>
    </select>
    

    This is a series of if-statements. There are probably other was of going around this, but this will work.

    EDIT: As you commented, this is a lot of work if you have many lines of options. If that's the case, you can use the following code to make PHP generate them.

    <select>
        <?php 
        $numRows = 30; // This is the number of options values you output
        for ($i=0; $i < $numRows; $i++) {
            echo "<option value=\"$i\"";
            if ($valueFromDB == "$i") 
                echo " selected"; 
            echo ">$i</option>";
        }
    ?>
    </select>
    

    This will output options equal to the value of $numRows. Note that it starts counting at 0.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?