Jump to content

get data from database to a radio button


mdvignesh
Go to solution Solved by scootstah,

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; ?>" />

 

 

 

Link to comment
Share on other sites

  • 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"?

Edited by PaulRyan
Link to comment
Share on other sites

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";
?>
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.