Adeniyi Ibraheem Adeniyi Ibraheem - 6 months ago 127
MySQL Question

online quiz using php and mysql(radio button)

please help, i'm developing an online quiz application. All the questions and answers will be selected from the database. Where i'm having probkem with is to get the values from the radio button whether checked or not. bellow is the code that generate the questions and answers from database.

if (!isset($_POST['submit'])) {
echo "<form method=post action='#'>";
echo "<table border=0>";
while ($row = mysql_fetch_array($display)) {
$id = $row["id"];
$question = $row["question"];
$opt1 = $row["ans1"];
$opt2 = $row["ans2"];
$opt3 = $row["ans3"];
$opt4 = $row["ans4"];
$opt5 = $row["ans5"];
$answer = $row["ans"];
echo "<tr><td colspan=3><br><b>$question</b></td></tr>";
echo "<tr><td>$opt1 <input type=radio name=q$id value=\"$opt1\"></td><td>$opt2 <input type=radio name=q$id value=\"$opt2\"></td><td>$opt3 <input type=radio name=q$id value=\"$opt3\"></td><td>$opt4 <input type=radio name=q$id value=\"$opt4\"></td><td>$opt5 <input type=radio name=q$id value=\"$opt5\">q$id</td></tr>";
}
echo "</table>";
echo "<input type='submit' value='See how you did' name='submit'>";
echo "</form>";
}


the name of the radio button is

<input type='radio' name='q$id' value='$opt4' />


How do i get the value of the checked radio button?
or is my PHP code wrong?
what i needed is to output what is selected if a radio button is checked.

if(isset($_POST['submit']))
{
$value = $_POST[''];//the value of the radio button, i don't know what to put here
$n = count($value);
for($i=0; $i < $n; $i++)
{
echo $value[$i];
}
}

Answer

Try:

if(isset($_POST['submit']))
{
    $value = $_POST;//the value of the radio button, i don't know what to put here
    $n = count($value);
   for($i=0; $i < $n; $i++)
   {
     echo $value[$i];
   } 
}

$_POST[''] was wrong. You needed to use just $_POST.

You could also just use foreach here:

if(isset($_POST['submit']))
{
    $values = $_POST;//the value of the radio button, i don't know what to put here

   foreach($values as $value)
   {
     echo $value;
   } 
}

$_POST is just a array containing whatever your form submited. If you had a name textfield you would use:

echo $_POST['name'];

to echo it.

Try

var_dump("<PRE>", $_POST);

And you will see exactly how your form is being organised. Link to documentation

Comments