Can radio button name attribute have numeric value - php

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.

Related

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

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.

Matching an input value with a form field value

I'm building an online quiz, I'm having trouble counting the number of correct values though. Each question has the following HTML:
<div class="form-group">
<label for="question <?PHP echo $question['id']; ?>"><?PHP echo $question['question']; ?></label>
<input type="hidden" value="<?PHP echo $question['answer']; ?>" name="original_number[]">
<input type="number" class="form-control" name="input_number[]" placeholder="<?PHP echo $question['question']; ?>" required>
</div>
There's a hidden input which contains the actual correct answer. I think I can get away with this as the quiz is a maths test for primary school children. The questions and answers are all stored in a database so my code loops through each question and outputs the above HTML for each one.
When it comes to actually submitting the form and then checking each input against the correct answer, everything I've tried so far doesn't seem to work, I've tried foreach looping around each question but that doesn't seem to work.
Ideally, each correct answer needs to add +1 to a variable. If that variable matches the total number of questions once the form has been submit, the test is marked as complete (I've already got the code in place for this).
Here's a couple of things I've tried:
foreach ($original as $key => $value) {
echo '<p>'.$key.'</p>';
foreach($value as $k => $v)
{
echo '<p>'.$k.'</p>';
echo '<p>'.$v.'</p>';
echo '<hr />';
}
^ Just outputs a list of numbers 0-12
foreach ($_POST as $key => $value) {
echo '<p>'.$key.'</p>';
foreach($value as $k => $v)
{
echo '<p>'.$k.'</p>';
echo '<p>'.$v.'</p>';
echo '<hr />';
}
This outputs 2 lists. The first list is 0-12 and then the value for original_number. The second list is also 0-12 and outputs the value for input_number.
Unless you are checking the answers with JS, there is no reason to put the answers in hidden inputs.
name your inputs to line up with the answers array and just loop over it all.

How to display value of checkbox array key using post to another php page?

I am currently displaying a table with checkbox and the checkbox is displayed using while loop. For the value of each checkbox, I used value = "$key" . The problem that I am currently having now is, how can I post the value of the checkbox to another php page ?`
<?php $sm_sql = "SELECT * FROM submodule WHERE mod_id = '1'";
$sm_res = DB_Query($sm_sql);
while($sm_row = DB_FetchRow($sm_res)) {?>
<tr> <?php
?> <td><div align="center"> <?php echo $sm_row["submod_name"];
?></div>
</td>
<!-- key 1 = submod_create_id -->
<td> <div align="center">
<?php
$fi_sql = mysql_query("SELECT * FROM finance_controlling WHERE staff_id = '".$STAFF_ID."'");
<?php
$fi_sql = mysql_query("SELECT * FROM finance_controlling WHERE staff_id = '".$STAFF_ID."'");
while($row = mysql_fetch_assoc($fi_sql))
{
foreach($row as $key => $value)
{
if($key == $sm_row["submod_create_id"])
{
if($value == '1')
{ ?><input type=checkbox checked="checked" name="$key" id="$key"> <?php
print $key; //it prints out the correct key
} else { ?><input type=checkbox name="$key" id="$key"> <?php
print $key;
}
}
}
}
?>
Above are my checkbox in Module_Form.php.
Below are Summary.php page where the value of the checkbox should be displayed on.
if ($_POST["Submit"] == "Review Risk")
{
$a = $_POST['fi_pp_c']; echo $a;
}?>
The problem now is that the checkbox value are not passed to another page. Ive tried json_encode but there are still no value displayed.
There are a few thing I feel should be addressed here.
First up: Prepared statements
Having raw SQL in your PHP code which just inserts variables inside some quotes is dangerous. It might be ok for your current use case, but in future if this changes, it is all too easy for a developer to just make $STAFF_ID a $_POST['varName'], which immediately introduces SQL injection.
Please take some time to read up on prepared statements and stored procedures in SQL/PHP: http://php.net/manual/en/pdo.prepared-statements.php
Second up: HTML attribute values
This is ok and it is valid HTML, however, I'd suggest it is good practice to include all attribute values in quotes, so that if there are spaces in values, they are correctly interpreted. This is clearly not going to happen with the type attribute but it does make code easier to read and to process using more primitative parsers, if it were:
<input type="checkbox" checked="checked" name="<?= $key ?>" id="<?= $key ?>">
As to the original question: have you enabled debugging? Primatively you can do this by adding error_reporting(E_ALL); to the top of your PHP file.
The issue I suspect you are facing is that is the checkbox is not checked, then there is no value for the key with the same name passed in the HTTP POST request.
For example, if you have:
<input type="checkbox" name="myCheckbox" />
And that checkbox is unchecked when the form is submitted, then in PHP $_POST['myCheckbox'] is null.
So the solution is to check whether these fields are null, e.g.:
if(isset($_POST['myCheckbox'])) {
$a = $_POST['myCheckbox'];
echo $a;
}
I generally think this is a gap in protocol, and that unchecked checkboxes should be submitted in forms with a value of 0, but ho hum!
In your code :
?><input type=checkbox checked="checked" name="$key" id="$key"> <?php
you closed your PHP tag and reopened it after the HTML.
You need to reopen it to print your $key in the name and id parameters. As it is, it`s only treated as text. The browser just thinks that the id and name attributes are "$key".
?><input type=checkbox checked="checked" name="<?= $key ?>" id="<?= $key ?>"> <?php
and here :
} else { ?><input type=checkbox name="<?=$key ?>" id="<?= $key ?>"> <?php
This would solve your current problem, as long as the "name" of the checkbox is "fi_pp_c" otherwise, it will be stored in whatever is named the checkbox.
You can just var_dump($_POST); to check where you data is stored if you still have issues.

Using foreach loop to checked checkbox answer

Currently, I have a column in database called answer to store all the answers for the form submitted. For now, the form itself have a "save" button whereby user can save the form if they're not free to finish it at the point of time. When the form is being saved, all the answers will be inserted into database.
Now my question is, my checkbox input answers are being inserted as example "1,2,3" if the question itself have option of "1,2,3,4,5". so I used a foreach loop to separate the data out and use if/else statement to check if it's same, marked as tick. But the question format end up to be like
x 1
2
x 2
3
3
x 3
4
4
4
5
5
5
The output that I want is:
x 1
x 2
x 3
4
5
The code for the printing of checkbox is like this:
First foreach is the options of the question, example "1,2,3,4,5".
Second foreach is the answers that the user selected after saving the form, example "1,2,3".
foreach ($arr as $row => $name) {
$arr = $name;
if ($input == 'Multiple choice (multiple answers) [Check box]') {
foreach ($arrAns as $values) {
if ($arr == $values) { ?>
<input type="checkbox" name="<?php echo 'qns' . $qID; ?>[]" value="<?php echo $arr; ?>" class="required" checked/> <?php echo $arr; ?><br/>
<?php break; } else { ?>
<input type="checkbox" name="<?php echo 'qns' . $qID; ?>[]" value="<?php echo $arr; ?>" class="required"/> <?php echo $arr; ?><br/>
<?php
} } } } ?>
Is it possible to get the output that I want? Thanks for the help!

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

Categories