简体   繁体   中英

PHP return selected field for drop down box

I'm having trouble with my php form that i query the info from the db which works fine now i just want when the user clicks submit to return the the selected value when the form reloads. I been trying to get this to work all night.

Example to be more clear.

--- Select ---

--- Apple ---

--- Banana ---

If they selected banana and clicked sumbit when the page reloads to have the field banana already selected. Here the code below. After 45 mins of fighting the "Parse error: syntax error, unexpected '.' I'm ready to pull my hair out so i hope you guys can lend a hand.

echo '<option value="'. $row['free'] .'" "'. $free==$row['free'] ? .'" selected=':'>$"'.$row['free'].'"</option>';

Thanks

echo '<option value="'. $row['free'] .'" "'. $free==$row['free'] ? /*.*/ '" selected=':'>$"'.$row['free'].'"</option>';

只是评论它,你可以看到它。

let's assume you have a select element within a form

<form action="" method="post">
       <select name ="fruits">
              <option value="apple">Apple</option>
              <option value="banana">Banana</option>
              <option value="orange">Oranges</option>
              <option value="mango">Mangoes</option>
       </select>
       <input type="submit" name="submit"/>
</form>

if i understand you correct you want to show the selected value back to the user when a user click on the submit button to do that place this in top of your php code.

<?php 
//This will check if form is submitted then fetch the value from select element else assign null
$value = isset($_POST['submit']) ? $_POST['fruits'] : NULL; 
?>

and change all the <option> to

<option value="apple" <?php echo ($value == 'apple') ? 'selected' : ''; ?>>Apple</option>
<option value="banana" <?php echo ($value == 'banana') ? 'selected' : ''; ?>>Banana</option>
<option value="orange" <?php echo ($value == 'orange') ? 'selected' : ''; ?>>Oranges</option>
<option value="mango" <?php echo ($value == 'mango') ? 'selected' : ''; ?>>Mangoes</option>
echo '<option value="' . $row['free'] . '"' . ($free == $row['free'] ? ' selected="selected"' : '') . '>' . $row['free'] . '</option>';

那应该工作:)

I'd advice you simplify your sintax and make it readable first of all.

$selected = '';
if($free==$row['free']){ $selected=' selected'; }

echo "<option value='{$row['free']}'{$selected}>{$row['free']}</option>";

Not sure how that string got into such a mess.... it's clearer (in my opionion) if you drop out of PHP mode if you're rendering HTML ... as follows:

?>
<option value="<?php echo $row['free']; ?>" <?php if($free == $row['free']) echo 'selected="selected"'; ?>><?php echo $row['free']; ?></option>
<?php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM