PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Hello, I am developing a app for school which you can create a practice test and use the Test ID to access your test, and I need help displaying the actually testing part. I want it so that the script pics a random question (one that hasn't been used before, and makes you answer that question (no refreshing to change the question) if your right it counts it correct, same for wrong. Whats below is what I have so far. All I need help with at this point is making the question "stay" the current question... any critiquing would be awsome!
Note: this isn't for actually testing, just for practice test so it doesn't have to be "cheat proof", but that would be nice
require has error messages that are printed out if the database doesn't connect so i'm just using the @ to shut it up if it says something for now. i'll fix that one the actual codes are done.
/**
* Start the session
*/
session_start();
if (!isset($_SESSION['answered'])) {
$_SESSION['answered'] = array();
}
/**
* Sanity check, make sure we have neccesary data
*/
if (!empty($_POST['answer']) && isset($_SESSION['currentQuestionId'])) {
/**
* However you update your database..
*/
$sql = 'UPDATE answers SET answer = \''. mysql_real_escape_string($_POST['answer']) .'\', question_id = '. intval($_SESSION['currentQuestionId']);
mysql_query($sql) or die(mysql_error());
/**
* Store then remove the current question id
*/
$_SESSION['answered'][] = $_SESSION['currentQuestionId'];
unset($_SESSION['currentQuestionId']);
}
/**
* This is to avoid the refreshing problem, if we have an active question fetch it
*/
if (isset($_SESSION['currentQuestionId'])) {
$sql = 'SELECT * FROM questions WHERE id = '. intval($_SESSION['currentQuestionId']);
}
/**
* We don't want to fetch answered questions..
*/
else {
$sql = 'SELECT * FROM questions WHERE id NOT IN ('. implode(', ', $_SESSION['answered']).') ORDER BY rand() LIMIT 1';
}
$result = mysql_query($sql) or die(mysql_error());
/**
* Check if we have any more questions left
*/
if (mysql_num_rows($result)) {
$question = mysql_fetch_assoc($result);
$_SESSION['currentQuestionId'] = $question['id'];
}
else {
//no questions left
}
Last edited by John Cartwright on Thu Aug 23, 2007 10:41 pm, edited 1 time in total.
I would recommend using the session for this. Initialize the random question order by shuffling an array. Maintain the current question number and the answers in the session as well. Using an object for this and saving it in the session will simplify keeping everything together.