Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- * Assuming data structure:
- *
- * mathbro
- * -------
- * id | question | answer1 | answer2 | answer3 | answer4 | is_right
- * ----------------------------------------------------------------
- *
- */
- /**
- * @param PDO $conn
- * @param integer $question_id
- * @param integer $selected_answer
- *
- * @return bool
- */
- function check_answer(PDO $conn, $question_id, $selected_answer) {
- //I'm doing it this way to not complicate things! Normally use prepared statements!
- $query = "SELECT `is_right` FROM `mathbro` WHERE `_id` = $question_id";
- //Preform query
- $stmt = $conn->query($query);
- //Fetch results
- $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
- //Testing logic
- if ($result["is_right"] == $selected_answer) {
- return true;
- }
- return false;
- }
- /**
- * @param PDO $conn
- * @param integer $question_id
- *
- * @return array
- */
- function fetch_question(PDO $conn, $question_id) {
- $query = "SELECT * FROM `mathbro` WHERE `_id` = $question_id";
- $stmt = $conn->query($query);
- $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
- return $result;
- }
- //DB connection. Using PDO here, better than MySQLi imo.
- try {
- $conn = new PDO("mysql:host=localhost;dbname=database", "root", "password");
- $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Set error reporting to exceptions. Helpful to find errors!
- }
- catch (PDOException $e) {
- die("Database connection failed! " . $e->getMessage());
- }
- //Check the current question
- $current_question = 1;
- if (isset($_POST["current_question"])) { //POST is set, question was answered.
- $current_question = $_POST["current_question"];
- //Check to see if answer is correct
- try {
- if (check_answer($conn, $current_question, $_POST["ans"])) { //Answer is correct
- $current_question++;
- }
- }
- catch (PDOException $e) {
- die("There was a problem! " . $e->getMessage());
- }
- }
- try {
- $question = fetch_question($conn, $current_question);
- ?>
- <form action="math.php">
- <?php
- if ($current_question == $_POST["current_question"]) { //Variable was not increased, answer isn't correct
- echo "<p class=\"error\">Incorrect! Try again!</p>";
- }
- ?>
- <label><input type="radio" name="ans" value="1"><?php echo $question["answer1"]; ?></label>
- <label><input type="radio" name="ans" value="2"><?php echo $question["answer2"]; ?></label>
- <label><input type="radio" name="ans" value="3"><?php echo $question["answer3"]; ?></label>
- <label><input type="radio" name="ans" value="4"><?php echo $question["answer4"]; ?></label>
- <input name="current_question" type="hidden" value="<?php echo $current_question; ?>">
- <button type="submit">Next</button>
- </form>
- <?php
- }
- catch (PDOException $e) {
- die("There was a problem! " . $e->getMessage());
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement