Using foreach loop to checked checkbox answer - php

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!

Related

How to display checked check boxes together with non-checked ones

I have 5 check boxes from which a user can select one or more choices. The selected choices are then updated in database. The user's choices are then displayed/reviewed on another page. However my issue is that I want to show the updated choices together with the non-selected choices when doing a foreach loop in PHP.
These are the 5 check boxes
<input type="checkbox" name="interest[]" value="fishing">Fishing
<input type="checkbox" name="interest[]" value="camping">Camping
<input type="checkbox" name="interest[]" value="hiking">Hiking
<input type="checkbox" name="interest[]" value="swimming">Swimming
<input type="checkbox" name="interest[]" value="running">Running
<br><br>
<input type="submit" name="submit" value="Submit">
Heres the code that updates
if (isset($_POST["submit"])) {
$interestArr = $_POST['interest'];
$interest = new Interest();
$newArr = implode(',', $interestArr);
$interest->updateInterests($id=19, $newArr);
}
Heres the code that displays
<?php
$interest = new Interest();
$interests = $interest->showInterests($userid=19)->interests;
$newArr = explode(',', $interests);
foreach ($newArr as $data) {
echo '<input type="checkbox" name="interest[]" value="'.$data .'" checked>'.$data;
}
The update choices are stored under the interests column in DB like so
fishing,camping,running
And the foreach loop displays them checked check box with the correct corresponding labels.
How can I display the other check boxes that were not selected just so that the user might want to make changes?
Thanks.
Here's a simple example to illustrate the main idea. This code is intended to run in the single script.
The main ideas are:
Use a global list of interests to drive the form.
Keep a separate global list of checked check boxes which you can compare to determine if the checkbox should be checked.
when the form is submitted, populate the list which keeps track of checked items
render the form and compare the list of available checkboxes with checked checkboxes. If item found in both lists, it means that we want to display the checkbox as checked.
index.php
<?php
// Keep this outside of the if statement so the form has access to it.
$availableInterests = [
'fishing',
'camping',
'hiking',
'swimming',
'running',
];
// Keep this outside of the if statement so the form has access to it.
$selectedInterests = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Cast the posted interests to an array in case the user submitted an empty list.
// An empty list would be NULL if we didn't cast it.
$selectedInterests = (array)$_POST['interest'];
// foreach $selectedInterests insert into DB...
// Let this code `fall through` to render the form again.
// $selectedInterests is now populated and can be used in to the form below to keep the selected checkboxes checked.
}
?>
<form method="post">
<!-- Using the `global` $availableInterests array to drive our form. -->
<? foreach ($availableInterests as $interest): ?>
<!-- Do we want to render the checkbox as checked? -->
<?php $checked = (in_array($interest, $selectedInterests)) ? ' checked' : ''; ?>
<input type="checkbox"
name="interest[]"
value="<?php echo $interest; ?>"
<?php echo $checked; ?>>
<?php echo ucfirst($interest); ?>
<?php endforeach; ?>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
Let's suppose you have an array of choice list like :
$choices = ["Fishing", "Camping" , "Hiking","Swimming" , "Running" ]
after the user select their choices
$interests = ["Fishing" , "Running" ];
In your case , the coresponding line is :
$interest = new Interest();
$interests = $interest->showInterests($userid=19)->interests;
$newArr = explode(',', $interests);
Let's suppose that $newArr is equal to $interests in may example.
foreach ($interests as $interest) {
echo 'you have choose '.$interest.PHP_EOL;
}
As result :
you have choose Fishing
you have choose Running
For not selected :
$notInterests = array_diff($choices,$interests);
foreach ($notInterests as $notInterest) {
echo 'you have not choose '.$notInterest.PHP_EOL;
}
As Result :
you have not choose Camping
you have not choose Hiking
you have not choose Swimming
To handle it in one loop :
foreach ($choices as $choice) {
if(in_array($choice,$interests )){
echo'you have choose '.$choice.PHP_EOL ;
}else{
echo 'you have not choose '.$choice.PHP_EOL;
}
}
Hope this help you.
To help others that might be in a similar situation I would like to post what is now a working solution at least for me based on Mohammed Yassine CHABLI's inspiration. Vantiya who was the first to comment really help me appreciate what was to follow. Thanks guys.
<?php
$interest = new Interest();
$interests = $interest->showInterests($userid=19)->interests;
$choices = $interest->showInterests($userid=19)->choices;
$selected = explode(',', $interests);
$choices = explode(',', $choices);
foreach ($choices as $choice) {
if(in_array($choice,$selected )){
echo '<input type="checkbox" name="interest[]" value="'.$choice .'"
checked>'.$choice;
}else{
echo '<input type="checkbox" name="interest[]" value="'.$choice .'"
unchecked>'.$choice;
}
}

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.

just show the input that was checked [duplicate]

This question already has answers here:
Getting checkbox values on submit
(10 answers)
Closed 6 years ago.
i am knew to php, and i want to know if there is a way to show the input based on the names that were checked, for example i have cat, dog and fish, if i choose dog and fish, i have to type the names of those animals.
here is the code to ask what animal do you have, and by checking and submit, it appears on the other page
<body>
<?php
$check_list[]=isset($_GET["check_list"])?$_GET["check_list"]:"";
if(!empty($_POST['check_list'])) {
foreach($_POST['check_list'] as $check) {
echo $check;
}
}
?>
<form action="names.php" method="POST">
<h1>choose the animals you have, and type their names</h1>
<input type="checkbox" name="check_list[]" value="cat">
cat
<br>
<input type="checkbox" name="check_list[]" value="dog" >
dog
<br>
<input type="checkbox" name="check_list[]" value="fish" >
fish
<br>
<input type="submit" value="next">
</form>
and here is the other page, that show what animals you have selected, and on this page i want to show the inputs based on the checked
<body>
<?php
echo '<h3>You have select following animals</h3>';
foreach ( $_POST ["check_list"] as $animals )
echo '<p>' . $animals . '</p>';
?>
So in your code,
just replace $check_list[]=isset($_GET["check_list"])?$_GET["check_list"]:""; with $check_list = isset($_POST["check_list"]) ? $_POST["check_list"] : ""; and you should be good.
Also your variable $animals always carry one animal so it should be named animal.
and this:
$check_list[]=isset($_GET["check_list"])?$_GET["check_list"]:"";
if(!empty($_POST['check_list'])) {
foreach($_POST['check_list'] as $check) {
echo $check;
}
}
can be improved to:
$check_list = isset($_GET["check_list"]) ? $_GET["check_list"] : null;
if ($check_list) {
foreach($check_list as $animal) {
echo "<p>My animal is: $animal</p>";
}
}
Next step is to learn more about security checks on user data!
Respectfully, good luck for you learning. PHP is beautiful ;)

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.

Categories