shd0w
shd0w

Reputation: 3

Incrementation In a php while loop

Hi Guys I was wondering if you could help me with incrementing within my while loop. I am programming an online quiz using php and want the qustion number to update every time they select the submit button but the variable $questionNumber only stays at one

My code is shown below

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

Hope you can help

Thanks

Upvotes: 0

Views: 282

Answers (2)

Mubo
Mubo

Reputation: 1070

You may change this part of your code to the following.

instead of : `

$_SESSION['number']=1;
$questionNumber = $_SESSION['number'];
$userScore=0;
$number= rand(1,4); 

write this :-

  $number= rand(1,4);
    $questionNumber = 0;
    if(isset($_SESSION['number']))
    {
        $_SESSION['number'] = $_SESSION['number'] + 1;
        $questionNumber = $_SESSION['number'];
    }else{
    $_SESSION['number'] = 1;
}

I think the problem is you are assigning the session to be equal to 1 before checking if it already set and valid session.

Hope that adds some

Upvotes: 0

jeroen
jeroen

Reputation: 91734

You are resetting the number at the start of your script:

$_SESSION['number']=1;

You need to change that to something like:

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

Upvotes: 5

Related Questions