0

I'm stuck for like 3 hours trying to find out why. The site I'm currently working on uses Mysql (deprecated) and I need to create registration form where users are required to answer a random test question pulled from the database before submitting the form. The database has [id/question/answer] columns.

I had written something like this:

$question_query = mysql_query("SELECT question FROM questions ORDER by RAND () LIMIT 1");
$question = mysql_result ($question_query, 0);

$answer_query = mysql_query("SELECT answer FROM questions WHERE question='$question'");
$answer = mysql_result ($answer_query, 0);

and then after all the checks

else {
$user_answer = $_POST['answer'];
if ($user_answer != $answer) {
$error = "Wrong answer";
}   
else {
$register = mysql_query("INSERT INTO user VALUES(blablabla)")
or die(mysql_error());
header("Location: register.php");
} 

When I hit submit it echos the $error = "Wrong answer". However, when I have only one question row in the database it works perfectly fine. As if the $question_query runs a random select all over again when I hit submit or something and thus renders the answer to that question false. Is there something I'm missing here?

Saul Tigh
  • 177
  • 8
  • Does the form submit to the same page? If so then yes, the queries will run again and generate a new question/answer. To be 100% sure though you need to add the entire file so there aren't any confusion about how it's structured – JimL Mar 18 '16 at 18:36

1 Answers1

1

However, when I have only one question row in the database it works perfectly fine.

That's because when you get a random element from a list of 1, it will always be the same element.

You're selecting a random question from the database and then comparing the answer of that question to the answer provided:

SELECT question FROM questions ORDER by RAND () LIMIT 1

So it's unlikely that the random question selected is going to be the same as the one which was previously asked. And that likelihood decreases as the number of questions increases. (50% chance with 2 questions, 25% chance with 4 questions, etc.)

When you originally show the question to the user, include in the form an identifier for the question. For example, if the table has an id column then you'd include that in the form. Something as simple as:

<input type="hidden" name="questionId" value="<?php echo $someQuestionId; " />

Then when the form is posted the identifier would be available here:

$_POST['questionId']

You'd use that value to make one query to the database, getting the answer for the question with that ID. Something like:

SELECT answer FROM questions WHERE id=$id

Important Note: Your current data access approach is wide open to SQL injection. You'll want to read this to better understand why this is a problem and how you can, very easily, correct it.

Community
  • 1
  • 1
David
  • 208,112
  • 36
  • 198
  • 279