skip to Main Content

I have multiple fields and created clones using jQuery. When I attempt to receive form data in PHP, all input data is received correctly. However, when it comes to radio buttons, only the response from the first field is received accurately. For the rest of the fields, I am receiving a value of 0.

My HTML Code

    <div class="row">    
    <div class="col-4">
        <div class="form-group optbox">
        <input type="radio" value="1" name="mcq[0]">
        <input type="text" name="opt-a[0]" placeholder="Option 1" required>
        </div>
    </div>
    <div class="col-4">
        <div class="form-group optbox">
            <input type="radio" value="2" name="mcq[0]">
        <input type="text" name="opt-b[0]" placeholder="Option 2" required>
        </div>
    </div>
    <div class="col-4">
        
        <div class="form-group optbox">
            <input type="radio" value="3" name="mcq[0]" >
        <input type="text" name="opt-c[0]" placeholder="Option 3" required>
        </div>
    </div>
</div>
    <div class="row">    
    <div class="col-4">
        <div class="form-group optbox">
        <input type="radio" value="1" name="mcq[1]">
        <input type="text" name="opt-a[1]" placeholder="Option 1" required>
        </div>
    </div>
    <div class="col-4">
        <div class="form-group optbox">
            <input type="radio" value="2" name="mcq[1]">
        <input type="text" name="opt-b[1]" placeholder="Option 2" required>
        </div>
    </div>
    <div class="col-4">
        
        <div class="form-group optbox">
            <input type="radio" value="3" name="mcq[1]" >
        <input type="text" name="opt-c[1]" placeholder="Option 3" required>
        </div>
    </div>
</div>

my PHP Coee:

$opts1 = $_POST['opt-a'];
$opts2 = $_POST['opt-b'];
$opts3 = $_POST['opt-c'];
$correct = $_POST['mcq'];
var_dump($correct);

result for var_dump

array(2) {[0]=>string(1) "3" [1]=> string(0) ""}

for radio button 1st value is correct but 2nd value is null

2

Answers


  1. try:

     $n = 5;
     $j = 0;
        while ($j <= $n) {
            $mcq = "mcq".$j;
            $correct = $_POST[$mcq];
            $j++;
        }
    
    Login or Signup to reply.
  2. By using the same name you will always get the value of the last input element.
    Use a name that describes an array, like:

    <input type="text" name="mcq[]" />
    

    In PHP, if you need to iterate over all this values, just use:

    foreach ($_POST["mcq"] as $value) {
       $correct = $value;
    }
    

    Or with the while:

    $n = 5; $j = 0;
    $mcq = $_POST['mcq'];
    while ($j <= $n) {
       $correct = $mcq[$j];
       $j++;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search