sql >> Database >  >> RDS >> Mysql

Dynamische waarden kiezen uit HTML-formulier en opslaan in PHP-variabelen

Ik denk dat je de vraag-ID gewoon als volgt moet posten:

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

Voor

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

Je moet toevoegen:

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

Volledige code

// 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());
    }
}
?>



  1. Hoe de functie Radians() werkt in PostgreSQL

  2. Waarom komen de resultaten van een SQL-query niet terug in de volgorde die ik verwacht?

  3. Redenen om Access-apps om te zetten in webgebaseerde apps

  4. Hoe meerdere queryresultaten om het querynummer te verminderen?