How to create a form with this question and save answers from / to the database

I am making a form that asks questions and answers from a database, I have several questions, but I want to answer one question on each page, and then move on to the next question. How can I make this possible? I need some advice.

My code for answering questions and answers is as follows:

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 in a database and shows the following question? or is there any function that can do this?

+5
source share
1 answer

depends on the case. If you want the user to stop along the way and maybe come back next time and finish it, then this is a good option. otherwise you can use the session to save your 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> 

SIMPLICITY BASIC demonstration of how a session can complete a task without a db request each time.

+1
source

Source: https://habr.com/ru/post/1239437/


All Articles