Diksha
Diksha

Reputation: 416

Radio button set's array created dynamically with echo in php. How to get their values?

I've created a php page which retrieves question and options(as MCQ's) from the database and in that Radio buttons are created dynamically using echo()
The name for each radio button group is assigned into an array from which one by one index's value is set to the name attribute.
Example:

$result=mysqli_query($db,$sql);
$numrows=mysqli_num_rows($result);//gets the number of questions
$radiogrp_name=array();

for($i=0;$i<$numrows;$i++){    //creating array of names for each set of radio buttons
    $radiogrp_name[$i]="q".$i;
}
$i=0;
while(($myrow=mysqli_fetch_array($result)) && ($i<$numrows)){
    echo $myrow["q_no"].". ";
    echo $myrow["ques"]."<br><br>";
    echo "<input type='radio' name='$radiogrp_name[$i]' value='a'/>".$myrow["A"]."<br>";
    echo "<input type='radio' name='$radiogrp_name[$i]' value='b'/>".$myrow["B"]."<br>";
    echo "<input type='radio' name='$radiogrp_name[$i]' value='c'/>".$myrow["C"]."<br>";
    echo "<input type='radio' name='$radiogrp_name[$i]' value='d'/>".$myrow["D"]."<br><br><br>";
    $i++;
    }

How would I get the selected radio buttons and set them into a SESSION variable? Can anyone help with this? Or any other way to implement this?
Thank you in advance!

Upvotes: 1

Views: 695

Answers (1)

dgeare
dgeare

Reputation: 2658

On the page that the form is POST'ed to you are going to need to look through the $_POST array and strip out the relevant answers. Ideally you would have a list of expected indexes to drive that page, but if not you could just try to pattern match the indexes.

Something like:

$results = array();
foreach($_POST as $key => $value){
    if(preg_match("/q(\d{1,3})/", $key, $matches)){
        $results[$matches[1]] = $value;
    }
}

results would then contain an array of values indexed by the numeral in name="q#" and you would just set it to the session or do with it whatever you need.

EDIT by the way, you'll need to wrap your string inclusion in curlies since it is an array.

echo "<input type='radio' name='{$radiogrp_name[$i]}' value='d'/>"

Upvotes: 1

Related Questions