tags:

views:

47

answers:

4

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

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

Pablo Morales
+2  A: 
<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
Davide Gualano
sweet, grazie Davide!
FFish
A: 

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.

Andy E
thanks for the tip Andy!
FFish
+1  A: 

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
Aaron W.
Actually Aarons example is exactly what I wanted, with default "M" checked. Typo though for the statement () ? :, not ;
FFish