Reputation: 299
<?php
$gender = $_GET['gender'];
$mysql_query = "select * from gender where value='$gender'";
$result = $conn->query($mysql_query);
while ($row = $result->fetch_assoc()) {
?>
<input type="radio" name="gender" value="<?php echo $row['value'];?>">
<?php
echo $row['value'];
}
?>
Lets assume the url is :- url.php?gender=male
the value in database are male, female, children
how do I make the male checked when the URL is passed
Upvotes: 0
Views: 54
Reputation: 812
just put condition on input radio <?php echo ($row['value']=='male' || $row['value']=='female' || $row['value']=='children' ) ? 'checked' : ''; ?>
<input type="radio" name="gender" value="<?php echo $row['value']; ?>" <?php echo ($row['value']=='male' || $row['value']=='female' || $row['value']=='children' ) ? 'checked' : ''; ?>><?php echo $row['value']; ?>
and same for female and children
Upvotes: 1
Reputation: 1144
Just set both checkbox's up and check the one that is set in the url
<input type="radio" name="gender" value="male" <?= (strtolower($_GET['gender']) === 'male' ? 'checked' : ''); ?>/>
<input type="radio" name="gender" value="female" <?= (strtolower($_GET['gender']) === 'female' ? 'checked' : '');?> />
I have just used short hand if statements inside the elements to test content of the gender param.
In response to your comment
I started writing a response to your comment and once i knew i needed code example Ive moved it here:
Short answer yes you would need to do it for every field instance.
But there is a dynamic loop option.
You would need to be able to able to build an array from your query that contained for each input element the type, name, value, checked. the array would need to look something like this:
<?php
$inputs = [
0 => [
'type' => 'radio',
'name' => 'gender',
'value' => 'male',
'checked' => true
],
1 => [
'type' => 'radio',
'name' => 'gender',
'value' => 'female',
'checked' => false
]
];
Now that your input array is defined you can loop through dynamically creating your inputs. Here I'm creating both inputs in a loop:
<?php foreach($inputs as $inp): ?>
<input type="<?= inp['type']; ?>" name="<?= $inp['name']; ?>" value="<?=$inp['name']; ?>" <?= $inp['checked'] ? 'checked' : ''; />
<?php endforeach; ?>
Because you of the way you are passing the gender in the URL
as GET
param you will probably have to go with my original answer at the top
Upvotes: 1