How to pass multiple checkbox values to php [duplicate] - php

This question already has answers here:
Get $_POST from multiple checkboxes
(5 answers)
Getting checkbox values on submit
(10 answers)
Closed 3 years ago.
Currently i have a HTML form that collects some metadata about some files, and each user as to fill some fields. I want to register some keywords about the data. I could ask them to write the keywords by hand on a normal text box, but i would prefer to have a list of checkboxes of about 10/15 values.
Then i need to pass only the checked values to a PHP file, using $_POST. My problem is that i assign a variable to those values, and then i call that variable in a DOM event. I´m generating a XML file, and currently i have the HTML ready to register these keywords in text input. I understand how to create the checkboxes, and pass them as an array to PHP., by reading other questions here. But i can´t understand how to pass this array to a $dom->createElement situation, and preferably separated by commas.
PHP
//Pull data from HTML form
$keywordsString = $_POST['keywords'];
// Creates xml document
$dom = new DOMDocument();
$dom->encoding = 'utf-8';
$dom->xmlVersion = '1.0';
$dom->formatOutput = true;
$xmlFileName = 'example_example.xml';
// Adds metadata to xml
$metadata = $dom->createElement('MD_Metadata');
$idInfo = $dom->createElement('identificationInfo');
$descriptiveKeywords = $dom->createElement('descriptiveKeywords');
$CharacterString = $dom->createElement('CharacterString', $keywordsString);
$descriptiveKeywords->appendChild($CharacterString);
$idInfo->appendChild($descriptiveKeywords);
$metadata->appendChild($idInfo);
$dom->appendChild($metadata);
$dom->save($xmlFileName);
I can´t figure out how to pass checkbox values to that $keywordsString , but separated by commas. The rest i can understand and write, using the other questions about this kind of issue.
Thanks in advance for all help provided.

Your html should look like this:
<form action="" method="post">
<input name="choice[]" type="checkbox" value="1" />
<input name="choice[]" type="checkbox" value="2" />
<input name="choice[]" type="checkbox" value="3" />
<input name="choice[]" type="checkbox" value="4" />
<input type="submit" value="order" />
</form>
In PHP, you can iterate over using foreach loop. Place the below code at the top of your html form:
A small note from basics, when posting data via post method, you need to apply Post redirect get design pattern to prevent form re-submissions.
If the data you are sending is not sensitive, you can do it via get request.
<?php
if($_POST):
foreach($_POST['choice'] as $val)
{
echo $val . "<br>";
}
endif;
?>

Related

PHP IF statement not working with _POST array

Having trouble with PHP (version is 5.6.27). My problem is I'm never getting into the IF loop, because the IF test fails, I assume because it's an array. I've tried using isset as well, to no avail.
if($_POST['product_new_quantity'] ){
foreach($_POST['product_new_quantity'] as $id => $new_quantity) {
if ($_POST['product_new_quantity'][$id] != $_POST['product_old_quantity'][$id]) {
// update the database with new value
}
}
}
Example data from the form looks like:
// BOF HTML FORM DATA - Formatted to display here.
// Yes I know It's missing the <> chars!
input type="hidden" name="product_old_quantity[62]" value="22"
input type="hidden" name="product_old_quantity[72]" value="11"
input type="hidden" name="product_old_quantity[3841]" value="64"
input type="text" name="product_new_quantity[62]" value="16"
input type="text" name="product_new_quantity[72]" value="15"
input type="text" name="product_new_quantity[3841]" value="58"
// EOF HTML FORM DATA
This apparently worked before on some prior version of PHP, but isn't anymore... and I REALLY don't want to have to refactor the entire report because these IF statements aren't working.
pleas check you have set form method post. => method="post"

How to gather multiple checkbox values in a form using php [duplicate]

This question already has answers here:
foreach checkbox POST in php
(2 answers)
Closed 7 years ago.
Im trying to gather checkbox informtion in a php form. Everythig else is working perfectly, but when selecting 5/10 checkboxes it only gives me the last one checked. When using "services[]" array, it just emails back "services:array"
Any ideas would be great.
Thanks.
(this is the PHP im using)
$name = $_POST['name'];
$email = $_POST['email'];
$number = $_POST['number'];
$services = $_POST['services'];
$message = $_POST['message'];
$changes = $_POST['changes'];
$found_me = $_POST['found_me'];
(this is the HTML thread)
<label>
<input type="checkbox" name="services[]" value="silver" class="silver">
Silver Pack (Website)
</label>
If you are posting any element with having square brackets [] in the end, you are posting an array of multiple elements.
You are posting checboxes with name services[], so you will get array in posted form.
Also, if you have 10 services checkboxes, only those will be posted which will be checked.
To deal with this HTML:
<input type="checkbox" name="services[]" value="silver" class="silver">
in PHP, use foreach loop for all checkboxes.
<?php
if (! empty($_POST['services'])) {
foreach ($_POST['services'] as $service) {
// YOU ARE GETTING POSTED VALUES HERE.
// NOW, $service will have values like: silver, ...
}
}
?>

Proper way to pass an array through post?

I have two pages:
Graph.php
List.php
The Graph page does exactly what it is named, graphs data. If there is no post/get data it displays all the data in a given table.
The List page is a huge table which loads around 500-600 rows of data. In the table you can sort and filter the rows using JavaScript. The table is around 14 columns wide.
After sorting the rows in the List page you can press a button 'Graph' that will take the visible rows and graph them on the graph page.
What I am having trouble with is passing these ID's over to the graph page. I started with:
<?php
if(isset($_POST['data']))
{
echo "FOUND SERIALIZED ARRAY<br>";
$afterSerializeArray = unserialize($_POST['data']);
print_r($afterSerializeArray);
}
$beforeSerializeArray = array();
$beforeSerializeArray[] = 1;
$beforeSerializeArray[] = 2;
$beforeSerializeArray[] = 3;
$serializeArray = serialize($beforeSerializeArray);
?>
<form action="" method="post">
<input type="hidden" name="data" value="<?php echo $serializeArray; ?>"/>
<input type="submit" value="Serialize"/>
</form>
I have written the small snippet to grab the ID's of the visible rows and load them into an array, serialize it and pump it into a variable to post it over to the graph.
Should I be using GET? Should I be doing this a different way?
The reason I wanted the filter and sort on a different page than the graph is because users have a lot of columns and options to filter and sort by.
Rather than trying to send array over post you should concatenate these ids with any special character (say ','). This way you will get all IDs as comma separated values in $_POST['data']. Now you can use PHP explode function to get all the values in an array and use them as you wish.
This code sample might help you
<?php
if(isset($_POST['data']))
{
echo "FOUND Ids<br>";
$IdArray = explode(',',$_POST['data']);
print_r($IdArray );
}
$idarray = array('1','2','3');
$ids = implode(',',$idarray);
?>
<form action="" method="post">
<input type="hidden" name="data" value="<?php echo $ids;?>"/>
<input type="submit" value="Serialize"/>
</form>

Modifying $_POST variable before submitting

I'm making a quiz generator, and I have an HTML form with radio buttons for multiple choice answers. Right now, when I submit my form, the contents of the $_POST variable looks like this when I submit it:
Array ( [a1] => Bob [a2] => Bobby )
(Bob and Bobby are the radio button choices I picked)
I'm generating this form using a PHP function, which returns an array of answers in addition to echoing the HTML form. Is there a way to modify the $_POST variable to have an 'answer' field (for checking my answers), like this:
Array( [a1] => Bob [a2] => Bobby [answers] => Array( [0] => Bob [1] => Bilbo ))
The above was one way I thought of to check answer array with $_POST array.
Edit: More info on what I have so far:
I have a PHP function getTest() that echoes the HTML form, and returns an array with the correct answers.
getTest() generates each question randomly, and as such the correct answers are random.
The main problem is that I have two separate PHP files, questions.php and verify.php.
questions.php echoes the form using getTest(), and has the array of answers.
verify.php only has the contents of $_POST, BUT NOT the array of correct answers.
Is there a better way to check the results of the form submission in general? Thanks!
The best way to do a quiz is to have an answers array and a user input array. Loop through one and compare to the other using the same increment.
You can take all of your post variables and create an array print_r($_POST); Then, loop through this.
$inputArray = //the post data into an array
$answerArray = array('a','b','a');
$numCorrect = 0;
for($a = 0; $a < count($inputArray); $a++)
{
if($inputArray[$a] == $answerArray[$a])
{
$numCorrect++;
}
}
If you want to transmit the answers when submitting the form, you could use inputs of hidden type (like ) which are invisible on the page. However it only takes the user checking the source HTML of the page to see these answers, so it might not be good for your use. Hope this helps
I think what you need to do is a have a look at sessions.
That way on questions.php you can save the answers to a session variable,
Then on verify.php you can read the answers from the session variable and compare them to answered supplied by the $_POST variable
If you really wanted to, you could probably just use a hidden field in your form for submitting an answer array. However, anyone can change your source and modify what the correct answer is.
The best way is to just have an array in your processing script with the same keys (a1, a2), but with the correct answers.
Your processing script would look like this:
$answers = array('a1'=>'Robert', 'a2'=>'Hobo');
foreach($_POST as $key => $value)
{
if (!array_key_exists($key, $answers))
{
continue;
}
if (trim($value) == $answers[$key])
{
// correct
}
else
{
// incorrect
}
}
If you want $_POST to contain an array you can simply use the bracket array notation on the name field of your form.
For example:
<fieldset class="Question1">
<input type="radio" name="answers[]" value="Question1Answer1">Question1Answer1<br>
<input type="radio" name="answers[]" value="Question1Answer2">Question1Answer2<br>
<input type="radio" name="answers[]" value="Question1Answer3">Question1Answer3<br>
</fieldset>
<fieldset class="Question2">
<input type="radio" name="answers[]" value="Question2Answer1">Question2Answer1<br>
<input type="radio" name="answers[]" value="Question2Answer2">Question2Answer2<br>
<input type="radio" name="answers[]" value="Question2Answer3">Question2Answer3<br>
</fieldset>
<fieldset class="Question3">
<input type="radio" name="answers[]" value="Question3Answer1">Question1Answer1<br>
<input type="radio" name="answers[]" value="Question3Answer2">Question1Answer2<br>
<input type="radio" name="answers[]" value="Question3Answer3">Question1Answer3<br>
</fieldset>
(Note that the fieldset tag is optional, I just included it to group things together)
The output in post will be an array $_POST['answers'] that will have one element for each question. So if you selected answer 1 for question 1, answer 2 for question 2, and answer 2 for question 3 you'd have:
$_POST['answers'] = [ 'Question1Answer1', 'Question2Answer2', 'Question3Answer2' ]
Not sure, but looks like you are asking for solution Y, whereas your problem is X (XY Problem)
The XY problem is when you need to do X, and you think you can use Y
to do X, so you ask about how to do Y, when what you really should do
is state what your X problem is. There may be a Z solution that is
even better than Y, but nobody can suggest it if X is never mentioned.
Usually it is not recommended to modify $_POST array, and also not to transmit Answers with the questions to client-side. Instead, the approach should be that because questions.php dont need answers, but verify.php does, so only verify.php shoul have access to answers.
For example, answer-lists are never transported to examination halls along with the question papers on the occasion of exams.
I have taken the liberty to modify your code structure. If you still want to go with your own code, please post it, and then you can get the answers you want.
Try to use this:
question.php:
<form action="verify.php" method="POST">
<fieldset class="Question1"> Complete this: ___<b>bar</b>
<input type="radio" name="answers[]" value="foo">Foo<br>
<input type="radio" name="answers[]" value="too">Too<br>
<input type="radio" name="answers[]" value="cho">Cho<br>
</fieldset>
<fieldset class="Question2"> Complete this: ___<b>overflow</b>
<input type="radio" name="answers[]" value="stack">Stack<br>
<input type="radio" name="answers[]" value="stock">Stock<br>
<input type="radio" name="answers[]" value="stick">Stick<br>
</fieldset>
</form>
answers.php:
//correct answers
$answers = array("foo", "stock");
verify.php:
include("answers.php");
$user_answers = $_POST["answers"];
$user_answers_count = count($user_answers);
$error = "";
for($i=0;$i<$user_answers_count;$i++)
if($user_answers[$i] !== $answers[$i]) //verify
$error[] = "Answer for Question ".($i+1)." is wrong!";
if(empty($error))
//Notify that user has passed the Quiz
else
//Notify that user has NOT passed the Quiz
//print the $error array
Couple of Notes:
I have used answers.php as a different file, but if there is no special requirement, consider merging answers.php & verify.php (put answers.php code on top of verify.php) Even better, you could also merge all these three files into one.
I have assumed that $_POST is sanitized.
Sequence of Questions & answers array is same. i.e. answers[foo] is correct answer for $_POST["answers"][foo]

PHP avoiding a long POST

This is more of a technique question rather than maybe code. I am having a php form with many fields (items to select). Naturally some of the items might be selected and some not. How do I know which ones are selected when i post the data from page 1 to page 2? I thought of testing each one if empty or not, but there are just too many fields and it doesn't feel at all efficient to use or code.
Thanks,
UPDATE EDIT:
I've tried the following and maybe it will get me somewhere before I carry on testing the repliers solutions...
<html>
<body>
<form name="test" id="name" action="testprocess.php" method="POST">
<input type="text" name="choices[shirt]">
<input type="text" name="choices[pants]">
<input type="text" name="choices[tie]">
<input type="text" name="choices[socks]">
<input type="submit" value="submit data" />
</form>
</body>
</html>
and then second page:
<?php
$names = $_POST['choices'];
echo "Names are: <br>";
print_r($names);
?>
This gives out the following:
Names are: Array ( [shirt] => sdjalskdjlk [pants] => lkjlkjlk [tie]
=> jlk [socks] => lkjlkjl )
Now what I am going to try to do is iterate over the array, and since the values in my case are numbers, I will just check which of the fields are > 0 given the default is 0. I hope this works...if not then I will let you know :)
I think what you're looking for is this:
<form action="submit.php" method="POST">
<input type="checkbox" name="checkboxes[]" value="this" /> This
<input type="checkbox" name="checkboxes[]" value="might" /> might
<input type="checkbox" name="checkboxes[]" value="work" /> work
<input type="submit" />
</form>
And then in submit.php, you simply write:
<?php
foreach($_POST['checkboxes'] as $value) {
echo "{$value} was checked!";
}
?>
The square brackets in the name of the checkbox elements tell PHP to put all elements with this name into the same array, in this case $_POST['checkboxes'], though you could call the checkboxes anything you like, of course.
You should post your code so we would better understand what you want to do.
But from what I understood you are making a form with check boxes. If you want to see if the check boxes are selected, you can go like this:
if(!$_POST['checkbox1'] && !$_POST['checkbox2'] && !$_POST['checkbox3'])
This looks if all the three check boxes are empty.
Just an idea:
Create a hidden input field within your form with no value. Whenever any of the forms fields is filled/selected, you add the name attribute of that field in this hidden field (Field names are saved with a comma separator).
On doing a POST, you can read this variable and only those fields present in this have been selected/filled in the form.
Hope this helps.
Try this.....
<?php
function checkvalue($val) {
if($val != "") return true;
else return false;
}
if(isset($_POST['submit'])) {
$values = array_filter(($_POST), "checkvalue");
$set_values = array_keys($values);
}
?>
In this manner you can get all the values that has been set in an array..
I'm not exactly sure to understand your intention. I assume that you have multiple form fields you'd like to part into different Web pages (e.g. a typical survey form).
If this is the case use sessions to store the different data of your forms until the "final submit button" (e.g. on the last page) has been pressed.
How do I know which ones are selected when i post the data from page 1 to page 2?
is a different question from how to avoid a large POST to PHP.
Assuming this is a table of data...
Just update everything regardless (if you've got the primary / unique keys set correctly)
Use Ajax to update individual rows as they are changed at the front end
Use Javascript to set a flag within each row when the data in that row is modified
Or store a representation of the existing data for each row as a hidden field for the row, on submission e.g.
print "<form....><table>\n";
foreach ($row as $id=>$r) {
print "<tr><td><input type='hidden' name='prev[$id]' value='"
. md5(serialize($r)) . "'>...
}
...at the receiving end...
foreach ($_POST['prev'] as $id=>$prev) {
$sent_back=array( /* the field values in the row */ );
if (md5(serialize($sent_back)) != $prev) {
// data has changed
update_record($id, $sent_back);
}
}

Categories