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.
Related
I have a problem with <form> in php .
i have uncertain number of fields (inputs) . it may be 1 or 100 input field .
Is there any function or class to get uncertain number of fields ?
Try that :
echo '<form>';
foreach ($data as $value) {
echo '<input name="field[]" value="',$value,'">';
}
echo '<input type="submit"></form>';
If you send that form, $_POST['field'] will be an indexed array in which every entry will correspond to one of the inputs.
$_POST would contain all the fields from the form on submit
print_r($_POST) will display them in an array for you
You can use an array name for the input fields in your form. For example, you can make an array of title fields by adding [] after the name:
<input type="text" name="title[]" />
<input type="text" name="title[]" />
<input type="text" name="title[]" />
Now in your PHP code, this value will be an array containing an amount of values equal to the number of fields with this name. The following code would print all titles on separate lines:
foreach ($_REQUEST['title'] as $value)
echo $value . "\n";
Just count the $_POST or $_GET what you use.
<?php
if(isset($_POST['submit'])){
echo "The total number of input fields is";
echo count($_POST); // include submit also
}
?>
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.
I have a front-end form submitting to my custom post type and checkboxes within.
<input type="checkbox" name="_my_checkbox[]" value="Yes"/> Yes
<input type="checkbox" name="_my_checkbox[]" value="No"/> No
<input type="checkbox" name="_my_checkbox[]" value="Maybe"/> Maybe
After that I saved it as post meta.
Then I need admin handling for this posts and values. As far as I've tried only accomplished to save and manipulate one value. I guess the problem is somewhere within the arrays.
Here it is a part of the function which displays the meta box.
$get_my_meta = get_post_meta($post->ID, 'my_meta', true);
$get_my_meta_data = array('Yes','No','Maybe');
foreach ($get_my_meta_data as $key => $value) { ?>
<input type="checkbox" name="_admin_my_checkbox[]" value="<?php echo $value;?>"<?php if($value == $get_my_meta){echo 'checked';} ?> /><?php echo $value;
}`
And then comes the saving function
if($_POST['_admin_my_checkbox']) {
$my_checkbox_updater = $_POST['_admin_my_checkbox'];
update_post_meta($post_id, 'my_meta', $my_checkbox_updater);
}
In this case when I check some of the checkboxes and use print_r values are saved as expected. I guess the problem is within foreach loop but have no idea what could be.
Quick edit. Found solution. in_array() function do the job perfectly.
foreach ($get_my_meta_data as $key => $value) { ?>
<input type="checkbox" name="_admin_my_checkbox[]" value="<?php echo $value;?>"<?php if(in_array($value,$get_my_meta)){echo 'checked';} ?> /><?php echo $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.
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!