views:

406

answers:

2

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>
+2  A: 

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.

jasonbar
+1 Good eye jasonbar. I didn't even notice that.
Anthony Forloney
A: 
<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.

Mark