shelum
shelum

Reputation: 163

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')";
}

Upvotes: 0

Views: 1443

Answers (2)

Dennis de Swart
Dennis de Swart

Reputation: 131

The checkbox form you use will produce a $_POST string "on" if checked: $_POST = array(["specialmem"]=> "on")

Your database however, is a BOOLEAN. You need to do an extra step for that, like: if($_POST["specialmem"] == "on"){ $specialmem =1; // the value to insert }

Plus the variable you try to insert into the database is called '$specialmember', should be '$specialmem'

Your gender radio button code seems to be OK. It should work.

Upvotes: 1

Sathvik Chinnu
Sathvik Chinnu

Reputation: 575

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>

Upvotes: 1

Related Questions