嗨,大家好,我想知道你是否可以帮助我在while循环中递增。我正在编写一个使用php的在线测验,并希望每次选择提交按钮时更新qustion数字,但变量$ questionNumber只保留在一个
我的代码如下所示
<?php session_start(); ?>
<html>
<head>
<title> World Cup Quiz </title>
</head>
<body>
<div align = center><strong> World Cup Quiz</strong></div>
<br />
<div align =center>
<?php
include ("dbConnect.php");
$_SESSION['number']=1;
$questionNumber = $_SESSION['number'];
$userScore=0;
$number= rand(1,4);
//search database for generated number and match ID
$dbQuery= "SELECT * FROM `questions 1.0` WHERE `ID` =$number";
$dbResult=mysql_query($dbQuery);
echo "Question:".$questionNumber."/5<br>";
//Assign variables to each attribute
while ($dbRow=mysql_fetch_array($dbResult))
{
$theID=$dbRow["ID"];
$theQuestion=$dbRow["Question"];
$theAnswer1=$dbRow["Correct Answer"];
$theAnswer2=$dbRow["Wrong Answer 1"];
$theAnswer3=$dbRow["Wrong Answer 2"];
$theAnswer4=$dbRow["Wrong Answer 3"];
$_SESSION['number']=$questionNumber+1;
}
//Print Questions and Answers
echo '<strong>'."$theQuestion".'</strong><br>';
?> <form name="correctAnswer" form method="post" action="quiz.php">
<?php
echo "$theAnswer1";?> <input type="radio" name="correctAnswer">
<?php
echo "<br>$theAnswer2"; ?> <input type="radio" name="wrongAnswer1">
<?php
echo "<br>$theAnswer3"; ?> <input type="radio" name="wrongAnswer2">
<?php
echo "<br>$theAnswer4"; ?> <input type="radio" name="wrongAnswer3">
<br><input type="submit" value="Submit Answer">
</form>
</div>
</body>
</html>
希望你能帮忙
由于
答案 0 :(得分:5)
您正在重置脚本开头的数字:
$_SESSION['number']=1;
您需要将其更改为:
if (!isset($_SESSION['number']))
{
$_SESSION['number']=1;
}
答案 1 :(得分:0)
您可以将代码的这一部分更改为以下内容。
代替: `
$_SESSION['number']=1;
$questionNumber = $_SESSION['number'];
$userScore=0;
$number= rand(1,4);
写下这个: -
$number= rand(1,4);
$questionNumber = 0;
if(isset($_SESSION['number']))
{
$_SESSION['number'] = $_SESSION['number'] + 1;
$questionNumber = $_SESSION['number'];
}else{
$_SESSION['number'] = 1;
}
我认为问题是您在检查会话是否已设置且有效会话之前将会话分配为等于1。
希望增加一些