0

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

2 Answers 2

5

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Works brilliantly is there a way to stop the loop if the incrementation hits a specific number like 6?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.