Mysql
 sql >> Base de données >  >> RDS >> Mysql

Choisir des valeurs dynamiques à partir du formulaire HTML et les stocker dans des variables PHP

Je pense que vous avez juste besoin de poster l'ID de la question comme ceci :

<input type="hidden"  name="q1" value="'$q1'">

Avant

$opt1=$_POST["answer$q1"]; 

Vous devez ajouter :

$q1=$_POST["q1"];
if (is_numeric($q1)) {
    $query = mysql_query("SELECT * FROM `microsoftq` WHERE QNo=".$q1);
    $rows1 = mysql_fetch_array($query);
    $ans1 = $rows1['Ans']; 
}

Code complet

// Build Form   
$nbQuestion = 2;
$form = '<form id="form1" name="quest" method="POST" action="" >';
$form .= getQuestion("SELECT * FROM `microsoftq`  ORDER BY RAND() LIMIT ".$nbQuestion);
$form .= '<input type="submit" id="submit_id" name="SUBMIT" value="SUBMIT"></form>';

// Save answer
if (isset($_POST['SUBMIT'])) 
{
    for($i=1;i<=$nbQuestion;$i++){
        saveAnswer($i);
    }
}
function getQuestion($query){
    $question = "";
    $i = 1;
    $result = mysql_query($query);
    while ($row = mysql_fetch_object($result)) {
        $question .= "<b>Question:-<br></b>".$row->Question." <br><br>";
        $question .= "<input type='hidden' name='q".$i."' value='".$row->QNo."'>";
        $question .= "<input type=radio name = 'answer".$row->QNo."' value = '".$row->Opt1."'></input>$a1 &nbsp &nbsp<br>"; 
        $question .= " <input type=radio name = 'answer".$row->QNo."' value = '".$row->Opt2."'></input>$b1 &nbsp &nbsp<br>"; 
        $question .= " <input type=radio name = 'answer".$row->QNo."' value = '".$row->Opt3."'></input>$c1 &nbsp &nbsp <br>"; 
        $question .= " <input type=radio name = 'answer".$row->QNo."' value = '".$row->Opt4."'></input>$d1 <br><br> ";
        $i++;
    }
    mysql_free_result($result);
}
function saveAnswer($nb){
    $qId=$_POST["q".$nb];
    if (is_numeric($qId)) {
        $query = mysql_query("SELECT * FROM `microsoftq` WHERE QNo=".$qId);
        $rows1 = mysql_fetch_array($query);
        $ans = $rows1['Ans'];
        $opt = $_POST["answer".$qId];
        if($ans==$opt)
        {
            $val="ct";
        }
        else
        {
            $val="wg";
        }
        mysql_query("insert into $username values('$qId','$opt','$val')")
        or die(mysql_error());
    }
}
?>