简体   繁体   中英

Test for registration page in php

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM