Quiz App - How to displaying a varying number of answer options? - php

I have database table which contains a number of questions each with corresponding answer options (multiple choice question). I am able to use PHP to extract a single question (with answer options) from the database, and would like to display one question at a time with the corresponding answer options to the user.
In my index.php file, I show the user the question using:
<?php echo $question["questionText"]; ?>
And I show the answer options using:
<input type="radio" name="optradio" value="<?php echo $question["option1"]; ?> <?php echo $question["option1"]; ?>
<input type="radio" name="optradio" value="<?php echo $question["option2"]; ?>"> <?php echo $question["option2"]; ?>
My issue is that the number of answer options (which are in form of radio buttons) varies per question with a maximum of 9 options.
What is the best way of ensuring that the user sees only however many options they need to see?

Instead of manually writing the below:
<input type="radio" name="optradio" value="<?php echo $question["option1"]; ?> <?php echo $question["option1"]; ?>
<input type="radio" name="optradio" value="<?php echo $question["option2"]; ?>"> <?php echo $question["option2"]; ?>
Just use a foreach loop here:
<?php foreach ($question as $option) { ?>
<input type="radio" name="optradio" value="<?php echo $option; ?>"> <?php echo $option; ?>
<?php } ?>
You should really do the following:
Retrieve the answers from the database.
(Optionally) Store it in an array.
Loop through it.
Echo out each option.
The above method will be both dynamic (each question has the right number) and also the right way.

Related

PHP - Form question population based on user answer

So I'm trying to create a fuel calculator form using PHP and HTML. For the most part, I have the form pretty fleshed out, however, I'm stuck on one thing.
So I would like to create a fuel perks option that gets input from the user. The question that I wanted to pose to the user is whether or not they purchased groceries. If the user types yes, then I wanted a different input box to appear asking the user for the amount in groceries that they spent and then calculate the fuel points based on that input. However, I can't figure out how to get the initial question of how much did they spend on groceries to appear based on their answer.
Here is what I have so far:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
How many miles did you drive? <input type="text" name="milesDriven" value="<?php echo $milesDriven;?>">
<span class="error">* <?php echo $milesDrivenErr;?></span>
<br><br>
What is your cars miles per gallon?:
<input type="text" name="milesPerGallon" value="<?php echo $milesPerGallon;?>">
<span class="error">* <?php echo $milesPerGallonErr;?></span>
<br><br>
Type of gas used:
<br><br>
<input type="radio" name="gasType" <?php if (isset($gasType) && $gasType=="87 octane - 1.89$/gal") echo "checked";?> value="1.89">87 octane - 1.89$/global
<br><br>
<input type="radio" name="gasType" <?php if (isset($gasType) && $gasType=="89 octane - 1.99$/gal") echo "checked";?> value="1.99">89 octane - 1.99$/global
<br><br>
<input type="radio" name="gasType" <?php if (isset($gasType) && $gasType=="92 octane - 2.09$/gal") echo "checked";?> value="2.09">92 octane - 2.09$/global
<br><br>
<input type="text" name="groceries"
<?php
if ($groceries = "yes") {
//code here that causes the input field to appear
}else if ($groceries = "no") {
//do nothing and proceed with the calculation
}
?>
<input type="submit" name="submit" value="Submit">
</form>
Can you create form inputs inside of a PHP block? Please forgive me if this is a dumb question. I'm still a beginner who's trying to learn more about backend coding.
Create a select tag inside the if block of yes and then calculate the amount the user has spend to purchase the groceries.
Can you create form inputs inside of a PHP block ? yes of course, you can just simply doing it like this
<?php
if ($groceries == "yes") {
echo "<input type='text' name='purchasedGroceries' value='".$purchasedGroceries."'">
}
?>
and calculate the fuel points when $groceries == "yes"

PHP foreach loop, need loop to get data from db, but it is also looping my forms

So I have a categories table in my database and each category has a certain amount of steps assigned to it. I want to have all of the categories displayed as tabs titled with the category name so I need this from the database. I then have a form inside the tabs to insert the amount of steps needed for that category, but this form is looping... I need it inside the foreach to get the category id but without the form looping... Hope that makes sense..
Here is my code:
<?php foreach($categories as $category){ ?>
<div id="<?php echo $category->category ?>" class="tab">
<form id="maxSteps" method="POST" name="maxSteps" action="<?php $PHP_SELF; ?>" enctype="multipart/form-data">
<label for="maxSteps">Amount of steps in form: </label><input style="width:50px;" id="maxSteps" type="text" name="maxSteps" />
<input type="hidden" name="catId" value="<?php echo $category->cat_id; ?>" />
<input type="Submit" value="Go" name="maxStepsSubmit" />
</form>
<table id="amountOfStepsForm">
<?php $maxStepsById = $wpdb->get_results( "SELECT * FROM metal_work_max_steps WHERE cat_id = '$category->cat_id'" ); ?>
<?php foreach($maxStepsById as $maxStep){ ?>
<tr><td id="maxStepsRow<?php echo $maxStep->id; ?>"><?php echo "<p>Amount of steps in form is: <b>".$maxStep->steps."</b>" ?></td><td id="editRow<?php echo $maxStep->id; ?>"><a id="<?php echo $maxStep->id; ?>" class='edit'>Edit</a></td></tr>
<input type="hidden" name="catId" value="<?php echo $category->cat_id; ?>" id="catId<?php echo $maxStep->id; ?>" />
<?php } ?>
</table>
</div>
<?php } ?>
Regards
The best thing you can do is to run only one query and retrieve all your data inside an associative array. Then just loop trough this data structure.
The query can be done using a JOIN statement, in order to retrieve the information regarding the max steps for each category.
1- put the Form tag above the for loop
2- <input type="hidden" name="catId" val... need to have dynamic name: name="catId_<?php echo $category->cat_id;?>"
3- the button Submit label GO, and the colse tag of Form need to be out of the for loop (below)
so all the fields will be in 1 form,
and you will have 1 submit button, if that what you need,
and the field names are not the same, so on submit you can read all of them
these are general comments, i think you need to pay attention to.

Can radio button name attribute have numeric value

Not sure if the question title is clear enough - but what I was referring to is - is it a bad practice to give a numeric value say 102 to the name attribute of a radio button like
<input type="radio" name="102" value="2032" /> Hello World
If it is a bad idea - the how do I handle this situation.
I have a multiple choice exam where all 60 questions are displayed on the page at once.
The questions are stored in a question array and for each question - the multiple choices are stored in an answer array
This is the for loop which generates the 60 questions with their multiple choice answers - right now I'm using question_id as the value for radio buttons
<?php
$question_ids = array_keys($this->question_array);
foreach($question_ids as $question_id)
{
$question = $this->question_array[$question_id];
$answers = $this->answer_array[$question_id];
?>
<div>
<strong>Q) <?php echo $question['question'];?></strong>
<div>
<?php foreach ($answers as $answer) { ?><br/>
<input type="radio" name="<?php echo $question_id;?>" value="<?php echo $answer['answer_id'];?>" /> <?php echo $answer['answer'];?>
<?php } ?>
</div>
</div>
<?php
} ?>
So I have assigned name with question_id and value with answer_id - so on server side - I will know for which question which answer option was selected - needless to say they are unique autogenerated id's from the database
foreach ($_POST as $key => $value)
echo "For question id ".htmlspecialchars($key)." answer selected is ".htmlspecialchars($value)."<br>";
If assigning number is a bad idea - why is that.
The other option for me is to assign a name value like name="questionId-102" and on the server side parse it.
Let me know what is the best way to handle this.
Thanks
A better practice would be to put it in an array of questions:
<?php foreach ($answers as $answer) { ?><br/>
<input type="radio" name="questions[<?=$question_id;?>]" value="<?=$answer['answer_id'];?>" /> <?=$answer['answer'];?>
And:
foreach ($_POST['questions'] as $key => $value)
echo "For question id ".htmlspecialchars($key)." answer selected is ".htmlspecialchars($value)."<br>";
You can use a simple string before the name in case you want a series or sequence of numbers. It is not advisable to use number as name for an element. Try using the following code
<?php
$question_ids = array_keys($this->question_array);
foreach($question_ids as $question_id)
{
$question = $this->question_array[$question_id];
$answers = $this->answer_array[$question_id];
?>
<div>
<strong>Q) <?php echo $question['question'];?></strong>
<div>
<?php foreach ($answers as $answer) { ?><br/>
<input type="radio" name="question_<?php echo $question_id;?>" value="<?php echo $answer['answer_id'];?>" /> <?php echo $answer['answer'];?>
<?php } ?>
</div>
</div>
<?php
} ?>
You can then use explode() function to get the question id for further process by using '_' as delimiter and second element of the array as question id.

HTML - PHP More than one multiple choice questn in a form, can select only one radio button.

Newbie here. I am trying to display more than one Multiple questions on a form with multiple choice answers displayed as radio buttons. A user should be able to select one answer(radion button) per question.
My problem is that once I display the questions and the answers, I can only select one radio button on the form(not per question). In the code below, qid is the question Id and aid is the answer Id. For each question retrieved from the database, the radio button group would get the question number assigned to the name.
For ex: question 1 has 4 multiple choice answers with name = 1 , question 2 has 4 multiple choice answers with name = 2 and so on.
So when the user selects an answer for question 1 and picks an answer to question 2, the selected answer for question 1 is cleared.
<body style="margin: 100px;">
<?php foreach ($questions as $question) : ?>
<small>(<?php echo $question['qid']; ?>)</small>
<strong><?php echo $question['qdesc']; ?></strong>
<ol>
<?php foreach ($answers[$question['qid']] as $answer) : ?>
<li><label><input type="radio" name=$question['qid'] value=$answer['aid']><?php echo $answer['adesc']; ?></label></li>
<?php endforeach; ?>
</ol>
<?php endforeach; ?>
</body>
Your radio button name has PHP code that is missing the opening and closing PHP tags (also missing quotes):
<li><label><input type="radio" name="q_<?php echo $question['qid']; ?>" value="<?php echo $answer['aid']; ?>"><?php echo $answer['adesc']; ?></label></li>
You might also want to include a prefix (as above) so that the names are not just numbers.
Because your radio groups all had the same name, it meant that were all treated as a single group and so only lets you select one.
as a small addition to the answer above.
<li>
<label for="qid_<?php echo $question['qid']; ?>">
<input type="radio" id="qid_<?php echo $question['qid']; ?>" name="q_<?php echo $question['qid']; ?>" value="<?php echo $answer['aid']; ?>">
<?php echo $answer['adesc']; ?>
</label>
</li>
now you can click on the text after the input in the label and the radio button will be selected.
label attribute [for] corresponding to the input attribute [id] within it

Insert Multiple data to mysql using a loop ...

so i have this code fragment here..
if($numTF > 0)
{
echo "TRUE-AND-FALSE QUESTIONS: Enter them below followed by their correct answer.";
echo "<br>";?>
<form method="post" action="" name="quizform">
<?php for ($i=1; $i<=$numTF; $i++)
{
echo "Question"." ".$i;
?>`
<p><textarea name='question<?php echo $i; ?>' rows=3 cols=90></textarea></p>
<input type="radio" name="answer<?php echo $i; ?>" value="True"> True
<input type='radio' name="answer<?php echo $i; ?>" value="False"> False<br><br><br>
<?php
}
}
... i am making a quiz maker in php...
the first thing to do is to set up the desired number of questions, so the value entered will go on the $numTF variable. Depending on the entered value, the textarea part will be printed. and there will be different names for each text area. AND THE CODE ABOVE IS WHERE U PRINT THE FORMS AFTER U ENTER THE DESIRED VALUE.
The next thing is to save that in a database. since the name of each textarea will be based on a variable value($i) that is used in a loop (name="answer") , HOW CAN I USE IT IN $_POST??? Like, would i do it like this?? ($_POST['question']).
HOW CAN I SAVE THESE QUESTIONS IN A DATABASE??
PLEASE HELP ME ....
I WOULD BE SO MUCH MUCH MUCH GRATEFUL FOR A LIL HELP.
<?
var_dump($_POST);
?>
<form method="post">
<?
$numTF=4;
if($numTF > 0)
{
echo "TRUE-AND-FALSE QUESTIONS: Enter them below followed by their correct answer.";
echo "<br>";?>
<form method="post" action="" name="quizform">
<?php for ($i=1; $i<=$numTF; $i++)
{
echo "Question"." ".$i;
?>`
<p><textarea name='question[<?php echo $i; ?>]' rows=3 cols=90></textarea></p>
<input type="radio" name="answer[<?php echo $i; ?>]" value="True"> True
<input type='radio' name="answer[<?php echo $i; ?>]" value="False"> False<br><br><br>
<?php
}
}
?>
<input type="submit" name="submit" value="submit"/>
</form>
Use $_POST['question'][1] // To get first question
Use $_POST['answer'][1] // To get first answer
Use loop to get all question and answers
I agree with Sachin as far as using name='question[]'. To answer question a little more as far as storing it in a database. Personally I would use a JSON array.
$store_answers = json_encode($_POST['answer']);
$store_questions = json_encode($_POST['question']);
Then just store $store_string in a TEXT field in your database. Then when you pull it back out of the database you can simple use:
$answers = json_decode($store_answers);
$questions = json_decode($store_questions);
Then you can loop through using a foreach like so:
foreach($questions as $key=>$question) {
echo "Question $key = {$answers[$key]} <br />";
}
This will display the results for each question.

Categories