1

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 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0
<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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.