shelum shelum - 2 months ago 26
PHP Question

Post data from radio buttons and check boxes into database

I have a form on a webpage that has radio buttons and a check box, and i'm trying to get that data inserted to a database when the form is submitted. When I submit the form the fields remain unchanged (default entry. All the other entries are inserted, just these two are giving me issues.

Table creation:

CREATE TABLE users (
gender varchar(255) NOT NULL,
specialmem BOOL NOT NULL,
) ENGINE=InnoDB;


Form:

<div class="form-group">
<label for="sex">Gender:</label>
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female" ) echo "checked";?>
value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male" ) echo "checked";?>value="male">Male
</div>
<div class="form-group">
<label for="specialmem">Are you a Special member?</label>
<input type="checkbox" name="specialmem" class="form-control" id="specialmem" value="1">
<button type="submit" class="btn btn-default">Submit</button>
</div>


Insert to database:

if(isset($_POST['submitted'])) {
$gender= $_POST['gender'];
$specialmem= $_POST['specialmem'];
$sqlinsert = "INSERT INTO users (gender, specialmem) VALUES ('$gender','$specialmember')";
}

Answer

Replace html code with the below code and then try it again

<div class="form-group">
    <label for="sex">Gender:</label>
    <input type="radio" name="gender" value="female" 
        <?php if(isset($gender)) { 
            if($gender='female') { 
                echo 'selected'; 
            } 
        } ?>
    >Female
    <input type="radio" name="gender" value="male" 
        <?php if(isset($gender)) { 
            if($gender='male') { 
                echo 'selected'; 
            } 
        } ?>
    >Male
</div>
<div class="form-group">
    <label for="specialmem">Are you a Special member?</label>
    <input type="checkbox" name="specialmem" value="1" class="form-control" id="specialmem" placeholder="">
    <?php 
        if(isset($_POST['specialmem'])) {
            if ($_POST['specialmem'] == '1') {
                $specialmem = $_POST['specialmem'];
            } else {
                $specialmem=0;
            }                   
        } 
    ?>
    <button type="submit" name="submitted" class="btn btn-default">Submit</button>
</div>
Comments