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 制裁名单20240508芯片厂商
  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接