php quiz having questions and answers in two different resultset

311 Views Asked by At

I am making a quiz which have questions and its options. Both questions and options are coming from database in resultsets. I am facing problems in loops and resultsets.

1 - I am not able to choose option out of each question. Whenever, I am selecting option from Question 1, I couldn't select option from Question 2.

2 - My page is reloading equals to the number of questions are in the quiz. As for example, I have two questions in quiz then page is reloading twice, if there are 5 questions then its reloading 5 times.

if(@$_GET['q']== 'quiz' && @$_GET['step']== 2) {
$eid=@$_GET['eid'];
$sn=@$_GET['n'];
$total=@$_GET['t'];
$a=1;
$b=0;
$q=mysqli_query($con,"SELECT count(*) FROM questions WHERE eid='$eid'" );
while($row=mysqli_fetch_array($q) ){
    $b=$row['count(*)'];
}
echo '<div class="panel" style="margin:5%">';
for($a=1;$a<=$b;$a++){
$q=mysqli_query($con,"SELECT * FROM questions WHERE eid='$eid' AND sn='$a' " );
while($row=mysqli_fetch_array($q) )
{
$qns=$row['qns'];
$qid=$row['qid'];
echo '<b>Question &nbsp;'.$a.'&nbsp;:<br />'.$qns.'</b><br />';
$q=mysqli_query($con,"SELECT * FROM options WHERE qid='$qid' " );
echo '<form action="update.php?q=quiz&step=2&eid='.$eid.'&n='.$sn.'&t='.$total.'&qid='.$qid.'" method="POST"  class="form-horizontal">
<br />';
while($row=mysqli_fetch_array($q) )
{
$option=$row['option'];
$optionid=$row['optionid'];
echo'<input type="radio" name="ans" value="'.$optionid.'">'.$option.'<br />';
}
echo '<br /><br />';
}
}
echo'<br /><button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-lock" aria-hidden="true"></span>&nbsp;Submit</button></form></div>';
}

Thanks for helping.

1

There are 1 best solutions below

2
On

So, right of the bat I see a few issues.

Easy SQL injection being the foremost. You use GET requests, so you take information from the URL. I can simply escape the quote, end that query and run a delete all right from the URL. You do this when you set $q.

How can I prevent SQL injection in PHP?

No need to do a while loop on a count() MySQL statement. It returns a single row.

You set $a and then set it again for the for loop. Look into foreach loops...

I am sorry but I cant help you with your code. It would need to be completely redone because there are other logical errors. You need to understand an html <form> and that you can only submit one form. Also, in HTML, an element's id must be unique. Which may be the reason you can only submit one question response. Also, you have many forms so that once you do find a way to answer your question, you will only submit one of them.

Almost seems like you tried to do everything in as little lines of code as possible, but you dont understand what you are doing yet.