TunaFFish
TunaFFish

Reputation: 11302

PHP form values after POST

I have a form on which I POST the data with PHP. When the data is send I want to show the new values. Doing this on textfields is easy, but how can I set the new values on the radioboxes. My default value is Male here.

PHP

if (isset($_POST['Submit'])) {
    update_user($_POST['name'], $_POST['sex']); // the update method
}

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 /><br />
  <label for="sex">Sex:</label>
  <input type="radio" checked="checked" name="sex" value="<?php echo (isset($_POST['sex'])) ? $_POST['sex'] : "M"; ?>" /> Male
  <input type="radio" name="sex" value="<?php echo (isset($_POST['sex'])) ? $_POST['sex'] : "F"; ?>" /> Female
</form>

Upvotes: 0

Views: 1390

Answers (4)

Aaron W.
Aaron W.

Reputation: 9299

Well you know the values of the Sex radioboxes...M and F. You want to see which one needs to be checked. This will default the checked to be Male like you currently have it.

<input type="radio" <?php echo (!isset($_POST['sex']) || $_POST['sex'] == "M") ? 'checked="checked"': ''; ?> name="sex" value="M" /> Male
<input type="radio" <?php echo (isset($_POST['sex']) && $_POST['sex'] == "F") ? 'checked="checked"': ''; ?> name="sex" value="F" /> Female

Upvotes: 1

Andy E
Andy E

Reputation: 344575

Try the following instead:

<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 /><br /> 
  <label for="email">Sex:</label> 
  <input type="radio" name="sex"<?php echo (@$_POST['sex'] == "M") ? 'checked="checked"' : "";?> value="M" /> Male 
  <input type="radio" name="sex" <?php echo (@$_POST['sex'] == "F") ? 'checked="checked"' : "";?> value="F" /> Female 
</form> 

Using the @ character means you don't need to use isset, it will suppress the warnings/errors if the variable isn't in the $_POST array.

Upvotes: 0

Davide Gualano
Davide Gualano

Reputation: 13003

<input type="radio" <?php if ($_POST['sex'] == "M") print "checked=\"checked\"";?> name="sex" value="M" /> Male
<input type="radio" <?php if ($_POST['sex'] == "F") print "checked=\"checked\"";?> name="sex" value="F" /> Female

Upvotes: 2

Pablo Morales
Pablo Morales

Reputation: 717

Try with print_r( $_POST );exit; to see the values sending in the variable POST.

Upvotes: -2

Related Questions