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条)

报告相同问题?