php html。 如何在
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?
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.
Just use "selected" attribute: http://www.w3schools.com/tags/att_option_selected.asp
If you are looping data and generating html from PHP, do something like this:
foreach($your_array as $info){
$add = NULL;
if($info['is_selected'] == 1){
$add = 'selected="selected"';
}
echo '<option value="'.$info['id'].'" '.$add.'>'.$info['name'].'</option>';
}