Jump to content

get data from database to a radio button


mdvignesh

Recommended Posts

I have page with male female radio button

 

Here's the code

 

$qry=mysql_query("SELECT * FROM reg_table where id=$id ");

$res=mysql_fetch_array($qry);

$radio = $res['gender'];

switch($radio)
{ 
   case "male":
   $mal = "checked";
   break; 
   case "female":
   $fem = "checked";
   break; 
} 

 

Gender: <br />
<input type="radio" name="colour" value="male" checked="<?php $mal; ?>" />Male
<input type="radio" name="colour" value="female" checked="<?php $fem; ?>" />Female

 

 

Whats the use of checked in

<input type="radio" name="colour" value="male" checked="<?php $mal; ?>" />

 

 

 

  • 1 year later...

Why keep jumping in and out of PHP tags dungpt29?

 

Use this, as it will not produce any errors when error reporting is turned on (and it should be)

<?PHP

  error_reporting(-1);

  $qry=mysql_query("SELECT * FROM reg_table where id=$id ");

  $res=mysql_fetch_array($qry);

  $radio = $res['gender'];

  switch($radio) {
    case 'male':
      $mal = true;
    break;
    case 'female':
      $fem = true;
    break;
  }

?>

Gender: <br />
<input type="radio" name="colour" value="male" <?php echo isset($mal) ? 'checked' : '' ; ?> />Male
<input type="radio" name="colour" value="female" <?php echo isset($fem) ? 'checked' : '' ; ?> />Female

*Edit - Should the name of the check boxes be "gender" and not "colour"?

The easiest way is use a loop, which is just the same code whether you have 2 or 200 options. The source for the loop can be a query or an array. For this example I'll use an array.

<?php
$qry=mysql_query("SELECT * FROM reg_table where id=$id ");
$res=mysql_fetch_array($qry);
$radio = $res['gender'];

$genders = array (
            'male'   => 'Male',
            'female' => 'Female'
            );

$genderOptions = '';
foreach ($genders as $val => $text) {
    $chk = $val==$radio ? "checked='checked'" : '';
    $genderOptions .= "<input type='radio' name='gender' value='$val' $chk />$text<br>";
}

echo "Gender<br>$genderOptions";
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.