У меня есть сценарий экзамена с несколькими вариантами ответов, который отлично работает, давая пользователю правильный / неправильный ответ. Единственное, чего не хватает, - это их счет.

Может ли кто-нибудь подсказать, как я могу добавить эту функцию - то есть дополнительный скрипт, который отражает оценку пользователей.

<?
$page_title = "The Simple Quiz Script";
// If the form is submitted run the script
if(isset($_POST['submit'])){
$quest1 = $_POST['quest1']; 
$quest2 = $_POST['quest2'];  
$quest3 = $_POST['quest3'];  
$quest4 = $_POST['quest4'];  
$quest5 = $_POST['quest5'];


// Lets make sure that everything has been submitted
// This might be the section that would need to be totaled to produce a score.

if($quest1 == NULL OR $quest2 == NULL OR $quest3 == NULL OR $quest4 == NULL OR $quest5 == NULL OR $quest6 == NULL OR $quest7 == NULL OR $quest8 == NULL OR $quest9 == NULL OR $quest10 == NULL){

$test_complete .='Please complete the quiz! You need to answer all the questions <a href="javascript:history.go(-1)">Go Back</a>';
}else{

// change the quest1 to the right answer
if($quest1 == "3") { 
$test_complete .="Question 'is this a agood script' is <span class='green'>correct</span>, well done!<br/>";  
}else{ 
$test_complete .="Question one 'is this a agood script' is <span class='red'>incorrect</span>!<br/>"; 
} 
// change the quest2 to the right answer
if($quest2 == "2") { 
$test_complete .="Question two is <span class='green'>correct</span>, well done!<br/>"; 
}else{ 
$test_complete .="Question two is <span class='red'>incorrect</span>!<br/>"; 
} 
// change the quest3 to the right answer
if($quest3 == "1") { 
$test_complete .="Question three is <span class='green'>correct</span>, well done!<br/>"; 
}else{ 
$test_complete .="Question three is <span class='red'>incorrect</span>!<br/>"; 
}
// change the quest4 to the right answer
if($quest4 == "3") { 
$test_complete .="Question four is <span class='green'>correct</span>, well done!<br/>"; 
}else{ 
$test_complete .="Question four is <span class='red'>incorrect</span>!<br/>"; 
}
// change the quest5 to the right answer
if($quest5 == "2") { 
$test_complete .="Question five is <span class='green'>correct</span>, well done!<br/>"; 
}else{ 
$test_complete .="Question five is <span class='red'>incorrect</span>!<br/>"; 
}

// Now lets see if all the questions are correct, this must match the above quest settings
if($quest1 == "3" & $quest2 == "2" & $quest3 == "1" & $quest4 == "3" & $quest5 == "2" & $quest6 == "3" & $quest7 == "2" & $quest8 == "1" & $quest9 == "3" & $quest10 == "2"){
$test_complete .="<p>Congratulations, you got all the questions correct!</p>"; 
}else{
// If any of the questions are not correct lets tell them
$test_complete .='<p>Your not there just yet! <a href="javascript:history.go(-1)">Try again</a></p>'; 
}}}
?>

Любые указатели здесь были бы очень признательны - я не уверен, с чего начать, и я очень новичок в php. Спасибо

+++++

Также! Просто добавлю ....

Этот код был изменен - ​​см. Ниже -

Этот код также пытается показать вопрос, заданный пользователем, и правильно ли он ...

    <?
$answers = array(); //Initialize array
    $answers[1] = "3";  //Set the answers
    $answers[2] = "3";
    $answers[3] = "3";
    $answers[4] = "3";  //Set the answers
    $answers[5] = "3";
    $answers[6] = "3";
    $answers[7] = "3";  //Set the answers
    $answers[8] = "3";
    $answers[9] = "3";
    $answers[10] = "3";

$questions=array("question 123","question 456","question 789");

    $score= 0;          //Initialize score

    for($i = 1; $i <= sizeof($answers); $i++) { //Start looping through the answers
        $answer = $answers[$i];                 //Get the correct answer for the current question
        $questions = $question[$i]               //Get the correct answer for the current question
        $index = "quest$i";                     //Slightly confusing here. You create a string with the current index, ie. quest1.
                                                //This will allow you to get the submitted answer in the POST request
        $submitted_answer = $_POST[$index];     //Get the submitted answer for this question

        if($answer === $submitted_answer) {     //If the answer is correct, increment score and add "Correct" response
            $test_complete .= "Question $i - $questions[$i] <span class='green'>correct</span>, well done!<br/>";
            $score++;  
        }
        else {
            $test_complete .="Question $i is <span class='red'>incorrect</span>!<br/>"; 
        }

    }

    if($score === sizeof($answers)) {           //All answers are correct
        $test_complete .="<p>Congratulations, you got all the questions correct!</p>"; 
    }
    else {                                      //Some answers are wrong
        $test_complete .='<p>Your not there just yet! <a href="javascript:history.go(-1)">Try again</a></p>';
    }

?>
php
-1
Henry 31 Июл 2014 в 21:23
1
Просто установите переменную = 0 в начале, увеличивайте ее при каждом правильном ответе, а затем выводите ее эхом.
 – 
General_Twyckenham
31 Июл 2014 в 21:27
Спасибо, я ценю вашу помощь.
 – 
Henry
31 Июл 2014 в 21:56
Без проблем. Ознакомьтесь с моим обновленным ответом, чтобы узнать о гораздо лучшем способе обработки модели вопрос-ответ.
 – 
General_Twyckenham
31 Июл 2014 в 22:01
Для дополнительного вопроса вам нужно будет сохранить вопрос и сопоставить (связать) его с правильным номером ответа. Например, если вы создали другой массив ($questions) и установили $question[$i]="Your question here", то при выводе вы бы добавили "Question $i - $questions[$i]..." или что-то в этом роде.
 – 
General_Twyckenham
31 Июл 2014 в 23:15
Спасибо, я думаю, что сделал хэш ... вы можете видеть, что мне не хватает? [большое спасибо, кстати] - я внес изменения выше
 – 
Henry
1 Авг 2014 в 00:27

2 ответа

Лучший ответ

Вот тривиальный способ сделать это, но я также включил гораздо лучший способ сделать это:

// change the quest1 to the right answer
$score = 0;  //Initialize the variable used to keep score.

if($quest1 == "3") { 
$score++;    //Increment the score by 1 at each correct answer
$test_complete .="Question 'is this a agood script' is <span class='green'>correct</span>, well done!<br/>";  
}else{ 
$test_complete .="Question one 'is this a agood script' is <span class='red'>incorrect</span>!<br/>"; 
}
...

echo "You got $score questions correct";  //Print out the score

Лучше всего задать вопросы в массиве . , чтобы вместо жесткого кодирования каждого ответа вы могли просто просмотреть их все в цикле:

$answers = array(); //Initialize array
    $answers[1] = "1";  //Set the answers
    $answers[2] = "3";
    $answers[3] = "1";

    $score= 0;          //Initialize score

    for($i = 1; $i <= sizeof($answers); $i++) { //Start looping through the answers
        $answer = $answers[$i];                 //Get the correct answer for the current question
        $index = "quest$i";                     //Slightly confusing here. You create a string with the current index, ie. quest1.
                                                //This will allow you to get the submitted answer in the POST request
        $submitted_answer = $_POST[$index];     //Get the submitted answer for this question

        if($answer === $submitted_answer) {     //If the answer is correct, increment score and add "Correct" response
            $test_complete .= "Question $i is <span class='green'>correct</span>, well done!<br/>";
            $score++;  
        }
        else {
            $test_complete .="Question $i is <span class='red'>incorrect</span>! The correct answer was $answer.<br/>"; 
        }

    }

    if($score === sizeof($answers)) {           //All answers are correct
        $test_complete .="<p>Congratulations, you got all the questions correct!</p>"; 
    }
    else {                                      //Some answers are wrong
        $test_complete .='<p>Your not there just yet! <a href="javascript:history.go(-1)">Try again</a></p>';
    }
1
General_Twyckenham 31 Июл 2014 в 23:11
Хотя это правильный ответ, объяснение значительно улучшит его.
 – 
11684
31 Июл 2014 в 21:38

Первая попытка

<?php
$page_title = "The Simple Quiz Script";
// If the form is submitted run the script
if(isset($_POST['submit'])){
$quest1 = $_POST['quest1']; 
$quest2 = $_POST['quest2'];  
$quest3 = $_POST['quest3'];  
$quest4 = $_POST['quest4'];  
$quest5 = $_POST['quest5'];

$score = 0;

// Lets make sure that everything has been submitted
// This might be the section that would need to be totaled to produce a score.

if($quest1 == NULL OR $quest2 == NULL OR $quest3 == NULL OR $quest4 == NULL OR $quest5 == NULL OR $quest6 == NULL OR $quest7 == NULL OR $quest8 == NULL OR $quest9 == NULL OR $quest10 == NULL){

$test_complete .='Please complete the quiz! You need to answer all the questions <a href="javascript:history.go(-1)">Go Back</a>';
}else{

// change the quest1 to the right answer
if($quest1 == "3") { 
$score++;
$test_complete .="Question 'is this a agood script' is <span class='green'>correct</span>, well done!<br/>";  
}else{ 
$test_complete .="Question one 'is this a agood script' is <span class='red'>incorrect</span>!<br/>"; 
} 
// change the quest2 to the right answer
if($quest2 == "2") { 
$score++;
$test_complete .="Question two is <span class='green'>correct</span>, well done!<br/>"; 
}else{ 
$test_complete .="Question two is <span class='red'>incorrect</span>!<br/>"; 
} 
// change the quest3 to the right answer
if($quest3 == "1") { 
$score++;
$test_complete .="Question three is <span class='green'>correct</span>, well done!<br/>"; 
}else{ 
$test_complete .="Question three is <span class='red'>incorrect</span>!<br/>"; 
}
// change the quest4 to the right answer
if($quest4 == "3") { 
$score++;
$test_complete .="Question four is <span class='green'>correct</span>, well done!<br/>"; 
}else{ 
$test_complete .="Question four is <span class='red'>incorrect</span>!<br/>"; 
}
// change the quest5 to the right answer
if($quest5 == "2") { 
$score++;
$test_complete .="Question five is <span class='green'>correct</span>, well done!<br/>"; 
}else{ 
$test_complete .="Question five is <span class='red'>incorrect</span>!<br/>"; 
}

// Now lets see if all the questions are correct, this must match the above quest settings
if($quest1 == "3" & $quest2 == "2" & $quest3 == "1" & $quest4 == "3" & $quest5 == "2" & $quest6 == "3" & $quest7 == "2" & $quest8 == "1" & $quest9 == "3" & $quest10 == "2"){
$test_complete .="<p>Congratulations, you got all the questions correct!</p>"; 
}else{
// If any of the questions are not correct lets tell them
$test_complete .='<p>Your not there just yet! <a href="javascript:history.go(-1)">Try again</a></p>'; 
}}}
echo "<p>Your score is: $score</p>";
?>

Короткие открывающие теги - баааад!

0
wbrzezin 31 Июл 2014 в 21:36
Спасибо. Кроме того, что вы подразумеваете под короткими открывающими тегами? Не могли бы вы объяснить, пожалуйста? Спасибо
 – 
Henry
31 Июл 2014 в 21:56
 – 
wbrzezin
1 Авг 2014 в 10:45