2013-12-09 175 views
0

嗨,大家好我想知道你是否可以幫助我在while循環內遞增。我使用PHP和希望qustion號碼更新每個他們選擇的時間提交按鈕,但變量$ questionNumber只停留在一個遞增在一個PHP while循環

我的代碼如下所示

<?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> 

希望你能編程的網上問答幫助

感謝

回答

5

你在你的腳本開始重新數量:

$_SESSION['number']=1; 

您需要更改爲類似:

if (!isset($_SESSION['number'])) 
{ 
    $_SESSION['number']=1; 
} 
+0

如果增量達到像6這樣的特定數字,出色的方法是停止循環嗎? – shd0w

+0

@ shd0w檢查'break':http://php.net/manual/en/control-structures.break.php – jeroen

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會話。

希望增加一些