Jaocampooo
Jaocampooo

Reputation: 481

Database wont update with PHP when there's multiple radios selected? Only the lastest radio selected will get updated

Let's say I have a form with 2 numbers and 4 radio buttons on each and only 1 option can be selected on each number.

When I submit, only the question 2's database will be updated. But if I leave #2 blank, question 1's database works or can be updated.

They only won't work if I submit them together.

The HTML Code

<div class="input-group">
<label class="question">1. <?php echo $question1 ?></label>
<div class="p-t-10">
<div>
<label class="radio-container m-r-45" ><?php echo $q1option1 ?>
<input type="radio" name="q1" value="c1">
<span class="checkmark"></span>
</label>
<label class="radio-container m-r-45"><?php echo $q1option2 ?>
<input type="radio" name="q1" value="c2">
<span class="checkmark"></span>
</label>
<div>
<div class="input-group">
<label class="question">2. <?php echo $question2 ?></label>
<div class="p-t-10">
<div>
<label class="radio-container m-r-45" ><?php echo $q2option1 ?>
<input type="radio" name="q2" value="c1">
<span class="checkmark"></span>
</label>
<label class="radio-container m-r-45"><?php echo $q2option2 ?>
<input type="radio" name="q2" value="c2">
<span class="checkmark"></span>
</label>
<div>

The PHP Code

$q1 = $_POST['q1'];

    if ($q1 == "c1" ) {

        $query = "UPDATE `question1` SET score = score + 1 WHERE choices = 'choice1'";
    }
    if ($q1 == "c2" ) {

        $query = "UPDATE `question1` SET score = score + 1 WHERE choices = 'choice2'";
    } 

$q2 = $_POST['q2'];

    if ($q2 == "c1" ) {

        $query = "UPDATE `question2` SET score = score + 1 WHERE choices = 'choice1'";
    }
    if ($q2 == "c2" ) {

        $query = "UPDATE `question2` SET score = score + 1 WHERE choices = 'choice2'";
    } 

They should be updating the score +1 everytime someone choices the option when submitted. How do I fix this? Please check my code.

Upvotes: 2

Views: 44

Answers (1)

Balvinder Singh
Balvinder Singh

Reputation: 320

You are using same variable for both questions so if both question submitted but last query will work as you defined same variable

$q1 = $_POST['q1'];
$query="";
$query2="";
if ($q1 == "c1" ) {

    $query = "UPDATE `question1` SET score = score + 1 WHERE choices = 'choice1'";
}
if ($q1 == "c2" ) {

    $query = "UPDATE `question1` SET score = score + 1 WHERE choices = 'choice2'";
} 
if($query){
//execute first query here
}

$q2 = $_POST['q2'];

if ($q2 == "c1" ) {

    $query2 = "UPDATE `question2` SET score = score + 1 WHERE choices = 'choice1'";
}
if ($q2 == "c2" ) {

    $query2 = "UPDATE `question2` SET score = score + 1 WHERE choices = 'choice2'";
} 
if($query2){
//execute second query here
}

Hope this helps you

Upvotes: 1

Related Questions