PHP Post help

Hi, i am new to php and i am trying to build a php quiz, that read question and answers from the mysql db.
so far i have the following code:

[php]require_once(“scripts/connect_db.php”);
session_start();
$_SESSION[‘Qid’] = 1;
if (!isset($_POST[‘answer’])){
$Qid = $_SESSION[‘Qid’];
echo $Qid;
$stmt = $dbh->prepare(“Select * FROM qtable WHERE id = ?”);
$stmt->bindParam(1, $Qid);
$stmt->execute();
$result = $stmt->fetchObject();
echo $result->Q . “
”;
$stmt = $dbh->prepare(“SELECT * FROM atable WHERE Qid = ? ORDER BY rand()”);
$stmt->bindParam(1, $Qid);
$stmt->execute();
$result = $stmt->fetchAll();
echo “<form action=“test1.php” method=“post”>”;
foreach ( $result as $row ) {
if ( $row[‘correct’] == 1 ){
echo “<input type=“radio” name=“answer” value=“1”>” .$row[‘answer’]."
";
} else {
echo “<input type=“radio” name=“answer” value=“0”>” .$row[‘answer’]."
";
}
}
echo “<input type=“submit” value=“next”>”;
echo “”;

} else {
if ( isset($_POST[‘answer’]) ) {

	$Qid = $_SESSION['Qid'] + 1;
	echo $Qid;
	$stmt = $dbh->prepare("Select * FROM qtable WHERE id = ?");
	$stmt->bindParam(1, $Qid);
	$stmt->execute();
	$result = $stmt->fetchObject();	
	echo $result->Q . "<br />";
	$stmt = $dbh->prepare("SELECT * FROM atable WHERE Qid = ? ORDER BY rand()");
	$stmt->bindParam(1, $Qid);
	$stmt->execute();
	$result = $stmt->fetchAll();
	echo "<form action=\"test1.php\" method=\"post\">";
	foreach ( $result as $row ) {
		if ( $row['correct'] == 1 ){
			echo "<input type=\"radio\" name=\"answer\" value=\"1\">" .$row['answer']."<br />";
		} else {
			echo "<input type=\"radio\" name=\"answer\" value=\"0\">" .$row['answer']."<br />";
		}
	}	
	echo "<input type=\"submit\" value=\"next\">";
	echo "</form>";
	
	} 

}[/php]

my idea is to increment $_SESSION[‘Qid’] by 1 every time i press submit so i can loop through the database, but so far i can only go up to the second row. Can anybody help me how to do this with out Jquery or AJAX.
Thanks

It looks like you are resetting the Qid to 1 every time you run the script.
I think you want to check to see if the session Qid is set first before setting to 1

if(!isset($_SESSION["Qid"])) 
    $_SESSION["Qid"]=1

This might be more useful:

[php] if(!isset($_SESSION[“Qid”]))
$_SESSION[“Qid”] +=1;[/php]

Since it sounds like you want some kind of increment to occur.

Wouldn’t that only execute once? Once a $_SESSION variable isset the if statement will be false?

True. That increment should be in the else clause. I didn’t notice the not before the is set function.

Also note that the query for the question is set up to pull a certain ID based on the Qid value,
but, it also randomly picks that ONE item. The random is not needed as you are only pulling one
value out. Unless you have many questions stored with that same ID?

Sponsor our Newsletter | Privacy Policy | Terms of Service