我正在學習編程,所以一個初學者。 下面我試圖用php和html創建一個簡單的測驗。每個問題需要刷新(每頁1個問題)。我試圖記錄總分,但只要頁面刷新(加載新問題),以前的分數就會消失。我不能讓我的測驗代碼工作
您能否告訴我我做錯了什麼,我應該怎麼做才能使它工作?
謝謝。
<?php
// get $pos from address bar
$pos = $_GET['position'];
if (!$pos) $pos = 0;
// showing the position (just to see to test.)
echo "position is $pos <br>";
$questions = array (
//Array for questions which include qID, calcType, qLayout, numbers (num1, num2,etc.), correctAns.
array (1, "Addition question", "add", "horizontal", array(1, 2, 3), array(1, "altAns"), array("hint1","hint2","hint3")),
array (1, "Addition question", "add", "horizontal", array(4, 5, 6), array(1, "altAns"), array("hint1","hint2","hint3")),
array (1, "Addition question", "add", "horizontal", array(7, 8, 9), array(1, "altAns"), array("hint1","hint2","hint3"))
);
$numOfQs= (sizeof($questions));
?>
<!doctype html>
<html>
<head>
<title>Maths Quiz</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<style>
.questionForm {
border:1px solid grey;
border-radius: 10px;
margin-top: 20px;
}
form {
padding-bottom: 20px;
}
p {
font-size:20px;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3 questionForm">
<form method="POST">
<div class="form-group">
<p>
<?php
// Generate question here.
echo "Question ".($pos+1)." of ".$numOfQs;
$question = $questions[$pos][1];
$calcType = $questions[$pos][2];
$qLayout = $questions[$pos][3];
$num1 = $questions[$pos][4][0];
$num2 = $questions[$pos][4][1];
$correctAns = $num1 + $num2;
echo "<h3>$question<br>".$num1." + ".$num2." = ? </h3>";
?>
</p>
<label for="yourAns">Your answer:</label>
<input type="text" name="yourAns" class="form-control" placeholder="Answer here." />
</div>
<input type="submit" name="submit" class="btn btn-success btn-lg" value="Submit" />
</form>
<div>
<p><?php
if ($_POST["submit"]) {
if($_POST["yourAns"]) {
$yourAns=$_POST["yourAns"];
if ($yourAns == $correctAns) {
echo "Your answer is correct!";
$correct[$pos] = 1;
} else {
echo "Your answer is wrong!</br> Correct answer is ".$correctAns.".";
$correct[$pos] = 0;
}
} else {
echo "Please enter your answer.";
}
// link to $pos + 1
echo '<br><a href="index.php?position='. ($pos+1) .'">Next page</a><br>';
$totalCorrect=$correct[0]+$correct[1]+$correct[2];
}
echo "Total correct is $totalCorrect <br>";
?> </p>
</div>
</div>
</div>
</div>
<?php
echo "Total correct is $totalCorrect <br>";
print_r($correct);
?>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>
在會話中存儲正確的總數,以便它在頁面之間保持不變。 –