Jag tror att du bara behöver posta fråge-ID så här :
<input type="hidden" name="q1" value="'$q1'">
Före
$opt1=$_POST["answer$q1"];
Du måste lägga till:
$q1=$_POST["q1"];
if (is_numeric($q1)) {
$query = mysql_query("SELECT * FROM `microsoftq` WHERE QNo=".$q1);
$rows1 = mysql_fetch_array($query);
$ans1 = $rows1['Ans'];
}
Komplett kod
// 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    <br>";
$question .= " <input type=radio name = 'answer".$row->QNo."' value = '".$row->Opt2."'></input>$b1    <br>";
$question .= " <input type=radio name = 'answer".$row->QNo."' value = '".$row->Opt3."'></input>$c1     <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());
}
}
?>