Homam Zraki
Homam Zraki

Reputation: 227

How to make a form with that picks questions and saves answers from/into database

I'm making a form that brings questions and answers from the database, i have several questions, but i want to answer one question on each page and then go to the next question. How can i make that possible? i need some tips.

My code for bringing the questions and answers looks like this:

echo "<form method='post'>";
	$sql= "SELECT pid, qid, question_link FROM question  ORDER BY qid ASC LIMIT 1";

$result = $mysqli->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_array()) {
	$pid1= $row['pid'];
	$qid1= $row['qid'];
	
	echo $row['question_link']."<br>";
	}
 
}

	$sql1= "SELECT pid, qid, aid, answer, points FROM answer_det WHERE pid=$pid1 AND qid=$qid1";

$result1 = $mysqli->query($sql1);

if ($result1->num_rows > 0) {
    while($row = $result1->fetch_array()) {
		$answer= $row['answer'];
		$aid= $row['aid'];
	echo "<input type='radio' name='answers' value='".$answer."'/>".$answer."<br>";
	}
 
}

echo "<input type='submit' value='Submit'></form>";

Should i make another PHP page that saves the data into the database and shows the next question? or is there any function that can make that?

Upvotes: 5

Views: 452

Answers (1)

Ghostff
Ghostff

Reputation: 1458

depends on the case. If you want the user to stop on the way and maybe come back next time and finish it up, then DB is a good option. else you can use session to store their progress.

<?php 
session_start();
if(isset($_POST['name'])){
    //store answers in session
    $new = (!empty($_SESSION['session_name']))? $_SESSION['session_name'].'|'.$_POST['name'] : $_POST['name'];
    //split session into an array
    $_SESSION['session_name'] = $new;
}
else if(isset($_POST['clear'])){
    if(!empty($_SESSION['session_name'])){
        unset($_SESSION['session_name']);
        echo "cleared";
    }
    else
        echo "Nothing to Clear";
}
if(!empty($_SESSION['session_name'])){
    var_dump($_SESSION['session_name']);
}
//finish the procees here befor storing into database;
//use foreach to itterate btw arrays and match anwers
//$_SESSION['session_name'] = explode('|', $_SESSION['session_name']);
//answer table $answers = array('a','b','c','d','e');
/* foreach($_SESSION['session_name'] as $key => $ans){
     if($ans == $answer[$key]){
        //right procesesor
     }
     else{
        //wrong procesesor
     }
} */
//handle the right and wrong process get to total score the store in db


?>
<form method="post" action="index.php">
   <input name="name" type="text" placeholder="">
   <input type="submit" value="submit">
</form>
<form method="post" action="index.php">
  <input type="submit" name="clear" value="clear">
</form>

SIMPLE BASIC demo of how session can get the job done without querying the db each time.

Upvotes: 1

Related Questions