Jump to content

Creating a quiz system with mysql and php (correction of code)


e-gab2

Recommended Posts

quizclass.php

First, we have taken variables for database credentials. Next, we have taken a constructor function for database connectivity code.

<?php

class Quiz {
    // Database credentials
    private $host = 'hostname';
    private $username = 'username';
    private $password = 'password';
    private $database = 'dbname';
    public $db;

    public function __construct()
    {
        if (!isset($this->db)) {
            // Connect to the database
            try {
                $this->db = new mysqli($this->host, $this->username, $this->password, $this->database);
            } catch (Exception $e) {
                $error = $e->getMessage();
                echo $error;
            }
        }
    }

    public function get_questions()
    {
        $select = "SELECT * FROM `questions` where is_enabled = '1' ";
        $result = mysqli_query($this->db, $select);
        return mysqli_fetch_all($result);
    }

    public function quiz_options($qid)
    {
        $select = "SELECT * FROM `quiz_options` where qid = '$qid' AND is_enabled = '1' ";
        $result = mysqli_query($this->db, $select);return mysqli_fetch_all($result);
    }
    
    public function answer($qid)
    {
        $select = "SELECT * FROM `quiz_answer` where qid = '$qid' ";
        $result = mysqli_query($this->db, $select);return mysqli_fetch_all($result);
    }
}

 

index.php

This is the main file that we will call in the browser. In this, we have imported the 'quizclass.php' and loop over the questions and options data. When the user submits the form, it will redirect to the 'score.php' page.

<html>
    <head>
        <title>PHP Multiple Choice Questions and Answers</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    </head>
    <body>
         <?php 
            include 'quizclass.php'; 
            $db = new Quiz(); 
            $quesions = $db->get_questions(); 
        ?>
        <div class="container">
            <h1>Multiple Choice Questions Answers</h1>
            <p>Please fill the details and answers the all questions-</p>
            <form action="score.php" method="post">
                <div class="form-group">
                    <?php 
                        foreach($quesions as $ques) { 
                            $options = $db->quiz_options($ques[0]);
                        }?> 
                        <h4><?php echo $ques[1]; ?></h4>
                        <div class="input-group-text" style="text-align: left; font-size: 18px;">
                        <ol>
                            <?php foreach($options as $option) {
                                echo "<li><input type='radio' name='".$option[2]."' value='".$option[1]."' required/> ".$option[3]."</li>"; 
                            }?> 
                        </ol>
                <div class="form-group">
                    <input type="submit" value="Submit" name="submit" class="btn btn-primary"/>
                </div>
            </form>
        </div>
    </body>
</html>

score.php

In this page, we collect the post data and calculate the score of the user. For this, we have imported the 'quizclass.php' database class file and compared the correct answer with the user's.

<?php
    include 'quizclass.php';
    $db = new Quiz();
    $score = 0;
    foreach ($_POST as $k=>$v) { 
        $answer = $db->answer($k);
        if ($answer[0][2] == $v) { 
            // option is correct 
            $score++; 
        } 
    } 
    $score = $score / 4 *100; 
    if($score < 50) { 
        echo '<h2>You need to score at least 50% to pass the exam.</h2>'; 
    } else { 
        echo '<h2>You have passed the exam and scored '.$score.'%.</h2>'; 
}

 

Link to comment
Share on other sites

  • gizmola changed the title to Creating a quiz system with mysql and php (correction of code)

I don't know if you have a question here.  In the future post code using the code tag button.

Some things I did when fixing your post:

Your index.php had a number of errors in the way the form markup was rendered.  You were also missing a php block end brace.

When you have a class file like the one you have for Quiz, then name that file Quiz.php.  I didn't change that in your code, but you should follow that practice going forward.

You probably want to replace the code you had, with what I put into your post (which I edited heavily).

If you have an actual question, you can follow up in this thread.

Link to comment
Share on other sites

15 hours ago, gizmola said:

I don't know if you have a question here.  In the future post code using the code tag button.

Some things I did when fixing your post:

Your index.php had a number of errors in the way the form markup was rendered.  You were also missing a php block end brace.

When you have a class file like the one you have for Quiz, then name that file Quiz.php.  I didn't change that in your code, but you should follow that practice going forward.

You probably want to replace the code you had, with what I put into your post (which I edited heavily).

If you have an actual question, you can follow up in this thread.

I have not seen the one you corrected.

Link to comment
Share on other sites

35 minutes ago, e-gab2 said:

I have not seen the one you corrected.

To get the most value from this forum it is best to actually read the replies given. Gizmola told you he had corrected your code in the initial post...

16 hours ago, gizmola said:

You probably want to replace the code you had, with what I put into your post (which I edited heavily).

 

Link to comment
Share on other sites

3 hours ago, e-gab2 said:

That is why I said I have not seen the one e he edited... 

Look at your original post.

The code for the 3 files is your original code, with edits by me.  In particular the index.php code was very broken and I made changes to that.  I don't guarantee that any of the code works, but I fixed obvious problems. 

Take the code from each block and replace the code in your original files, and test.

Link to comment
Share on other sites

Database

A database needs to be created to store the information about questions, options and correct answers. So let's create a database using the following query. Here is a table 'questions' that contains all the quiz questions.

CREATE TABLE IF NOT EXISTS `questions` ( `qid` int(11) NOT NULL AUTO_INCREMENT, `question` varchar(150) NOT NULL, `is_enabled` int(11) NOT NULL, PRIMARY KEY (`qid`) ) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

 

INSERT INTO `questions` (`qid`, `question`, `is_enabled`) VALUES (1, 'Which function is used to reverse the order of elements in an array?', 1), (2, 'Which function is used to return character from the ASCII value?', 1), (3, 'Which function is used to check the existence of a constant?', 1), (4, 'Which function is used to return the last element of an array?', 1);

 

Here is a table 'quiz_options' that contains all the quiz options -

CREATE TABLE IF NOT EXISTS `quiz_options` ( `option_id` int(11) NOT NULL AUTO_INCREMENT, `qid` int(11) NOT NULL, `option` varchar(150) NOT NULL, `is_enabled` int(11) NOT NULL, PRIMARY KEY (`option_id`) ) ENGINE=MyISAM AUTO_INCREMENT=17 DEFAULT CHARSET=latin1;

 

INSERT INTO `quiz_options` (`option_id`, `qid`, `option`, `is_enabled`) VALUES (1, 1, 'array_rev()', 1), (2, 1, 'array_reverse()', 1), (3, 1, 'reverse()', 1), (4, 1, 'array_end()', 1), (5, 2, 'chr()', 1), (6, 2, 'ascii()', 1), (7, 2, 'asc()', 1), (8, 2, 'return_chr()', 1), (9, 3, 'define()', 1), (10, 3, 'const()', 1), (11, 3, 'defined()', 1), (12, 3, 'exist()', 1), (13, 4, 'end()', 1), (14, 4, 'arr_end()', 1), (15, 4, 'last()', 1), (16, 4, 'end()', 1);

 

At last, we create a table 'quiz_answer' for storing the correct answer of the quiz -

CREATE TABLE IF NOT EXISTS `quiz_answer` ( `qa_id` int(11) NOT NULL AUTO_INCREMENT, `qid` int(11) NOT NULL, `option_number` int(11) NOT NULL, PRIMARY KEY (`qa_id`) ) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

 

INSERT INTO `quiz_answer` (`qa_id`, `qid`, `option_number`) VALUES (1, 1, 2), (2, 2, 1), (3, 3, 3), (4, 4, 4);




 

 

Edited by e-gab2
Link to comment
Share on other sites

 

I used your database structure and values.  You have an issue with the data in quiz_answer.  I am going to leave it to you to figure out what is wrong

(Hint:  the answers need to match the correct option_id!)

Here are the files I used.  You will need to have valid database host, name, password and db variables defined in the quiz class, so that you are connecting to the database. 

One thing you need to understand is that when you submit a form ALL the fields in the form are submitted, including buttons.  Everything will be in the $_POST array. 

I added a line of code to deal with this problem.

I also added some code to display the grading step for each question, so you can better understand what is happening.

Some good functions you can use to help you with simple debugging:

When you don't understand what a variable contains try adding print_r($variable);die();

This will show you the value of the variable and stop processing.  You don't have to stop processing, but having a lot of these statements is often confusing.  Solve one issue and move on to the next.

The biggest issue with this code is the use of numeric indexing of your mysql data with mysqli_fetch_all.  Things would be better if your mysqli fetch routines used mysqli_fetch_all($result, MYSQLI_ASSOC);

Working with array keys is much clearer, not to mention safer than having code like:  (if $somevar == $array[0][2]).  That code would be something like $somevar == $array[0]['option_number'] instead.

 

//quizclass.php
<?php

class Quiz {
    // Database credentials
    private $host = 'hostname';
    private $username = 'username';
    private $password = 'password';
    private $database = 'dbname';
    public $db;

    public function __construct()
    {
        if (!isset($this->db)) {
            // Connect to the database
            try {
                $this->db = new mysqli($this->host, $this->username, $this->password, $this->database);
            } catch (Exception $e) {
                $error = $e->getMessage();
                echo $error;
            }
        }
    }

    public function get_questions()
    {
        $select = "SELECT * FROM `questions` where is_enabled = '1' ";
        $result = mysqli_query($this->db, $select);
        return mysqli_fetch_all($result);
    }

    public function quiz_options($qid)
    {
        $select = "SELECT * FROM `quiz_options` where qid = '$qid' AND is_enabled = '1' ";
        $result = mysqli_query($this->db, $select);
        return mysqli_fetch_all($result);
    }
    
    public function answer($qid)
    {
        $select = "SELECT * FROM `quiz_answer` where qid = '$qid' ";
        $result = mysqli_query($this->db, $select);
        return mysqli_fetch_all($result);
    }
}
//index.php
<html>
    <head>
        <title>PHP Multiple Choice Questions and Answers</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    </head>
    <body>
         <?php 
            include 'quizclass.php'; 
            $db = new Quiz(); 
            $quesions = $db->get_questions(); 
        ?>
        <div class="container">
            <h1>Multiple Choice Questions Answers</h1>
            <p>Please fill the details and answers the all questions-</p>
            <form action="score.php" method="post">             
                <?php
                    foreach($quesions as $ques) { 
                        $options = $db->quiz_options($ques[0]);
                        
                ?>        
                        <div class="form-group">
                            <h4><?php echo $ques[1]; ?></h4>
                            <div class="input-group-text" style="text-align: left; font-size: 18px;">
                            <ol>
                                <?php foreach($options as $option) {
                                    echo "<li><input type='radio' name='".$option[1]."' value='".$option[0]."'> ".$option[2]."</li>";
                                }?> 
                            </ol>
                        </div>
                <?php        
                    } //end foreach
                ?> 
                <div class="form-group text-center">
                    <input type="submit" value="Submit" name="submit" class="btn btn-primary"/>
                </div>
            </form>
        </div>
    </body>
</html>

  

//score.php
<?php
    include 'quizclass.php';
    $db = new Quiz();
    $score = 0;

    foreach ($_POST as $k => $v) {
        if (is_int($k)) { 
            $answer = $db->answer($k);
            if ($answer[0][2] == $v) { 
                // option is correct
                echo "Question {$answer[0][1]} was correct.<br>"; 
                $score++; 
            } else {
                echo "Question {$answer[0][1]} was wrong.<br>";
            }
        } 
    }

    $score = $score / 4 *100; 
    if($score < 50) { 
        echo '<h2>You need to score at least 50% to pass the exam.</h2>'; 
    } else { 
        echo '<h2>You have passed the exam and scored '.$score.'%.</h2>'; 
}

 

  • Great Answer 1
Link to comment
Share on other sites

1 hour ago, ginerjm said:

Gizmola - you have way too much time on your hands.  I do hope it is appreciated by the OP.

It was something I used to test out a docker project I've been working on, so it really didn't take long.  Gave me an excuse to play with it.

Link to comment
Share on other sites

I keep having this response when I execute the index.php code - "undefined variable $ques". Please help me check the entire code. I have done my best to this extent. After checking please run it to be sure it works. I'm working on this project. I want to use it to build an app for reading and answering of quizes. 

Link to comment
Share on other sites

7 hours ago, e-gab2 said:

I keep having this response when I execute the index.php code - "undefined variable $ques". Please help me check the entire code. I have done my best to this extent. After checking please run it to be sure it works. I'm working on this project. I want to use it to build an app for reading and answering of quizes. 

I already debugged this for you.  Did you use the code I posted?  It was tested, and doesn't have any bugs involving the $ques variable being undefined.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.