I have a form with 'selected' values pulled from the database.
Now I want the user to edit the values. When the data is send I want to show the new values.When I submit my form I always get the 'green' value?
What am I doing wrong here?<?php
// pulled from db
$color = "blue";
// update
if (isset($_POST['Submit'])) {
echo "write to db: " . $_POST['name'] . " + " . $_POST['color'];
}
?>
<html>
<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="name">Name:</label>
<input type="text" name="name" size="30" value="<?php echo (isset($_POST['name'])) ? $_POST['name'] : ""; ?>">
<br />
<label for="color">Color:</label>
<select name="color">
<option <?php echo (isset($_POST['color']) || $color == "red") ? 'selected="selected"' : ''; ?> value="red">red</option>
<option <?php echo (isset($_POST['color']) || $color == "blue") ? 'selected="selected"' : ''; ?> value="blue">blue</option>
<option <?php echo (isset($_POST['color']) || $color == "green") ? 'selected="selected"' : ''; ?> value="green">green</option>
</select>
<br />
<input type="submit" name="Submit" value="Update">
</form>
</html&g开发者_开发问答t;
Your conditionals all use ||
. They all evaluate to TRUE when the post is set. If you look at the HTML output, every option will say selected='selected'
.
Just compare $_POST['color']
to your specified string.
<option <?php echo (isset($_POST['color']) || $color == "red") ? 'selected="selected"' : ''; ?> value="red">red</option>
||
is the "or" operator. If $_POST['color']
is set (i.e., the form was submitted), that will always evaluate to true. You should probably just do
$_POST['color'] == 'red'
Instead. Forget the isset
check.
精彩评论