getting a checkbox array value from POST - php

i am posting an array of checkboxes. and i cant get it to work. i didnt include the proper syntax in the foreach loop to keep it simple. but it is working. i tested in by trying to do the same thing with a text field instead of a checkbox and it worked with the textfield.
<form method="post">
<?php
foreach{
echo'
<input id="'.$userid.'" value="'.$userid.'" name="invite[]" type="checkbox">
<input type="submit">';
}
?>
</form>
here is the part that is not working. it is echoing 'invite' instead of array.
<?php
if(isset($_POST['invite'])){
$invite = $_POST['invite'];
echo $invite;
}

Your $_POST array contains the invite array, so reading it out as
<?php
if(isset($_POST['invite'])){
$invite = $_POST['invite'];
echo $invite;
}
?>
won't work since it's an array. You have to loop through the array to get all of the values.
<?php
if(isset($_POST['invite'])){
if (is_array($_POST['invite'])) {
foreach($_POST['invite'] as $value){
echo $value;
}
} else {
$value = $_POST['invite'];
echo $value;
}
}
?>

I just used the following code:
<form method="post">
<input id="user1" value="user1" name="invite[]" type="checkbox">
<input id="user2" value="user2" name="invite[]" type="checkbox">
<input type="submit">
</form>
<?php
if(isset($_POST['invite'])){
$invite = $_POST['invite'];
print_r($invite);
}
?>
When I checked both boxes, the output was:
Array ( [0] => user1 [1] => user2 )
I know this doesn't directly answer your question, but it gives you a working example to reference and hopefully helps you solve the problem.

Check out the implode() function as an alternative. This will convert the array into a list. The first param is how you want the items separated. Here I have used a comma with a space after it.
$invite = implode(', ', $_POST['invite']);
echo $invite;

// if you do the input like this
<input id="'.$userid.'" value="'.$userid.'" name="invite['.$userid.']" type="checkbox">
// you can access the value directly like this:
$invite = $_POST['invite'][$userid];

Because your <form> element is inside the foreach loop, you are generating multiple forms. I assume you want multiple checkboxes in one form.
Try this...
<form method="post">
foreach{
<?php echo'
<input id="'.$userid.'" value="'.$userid.'" name="invite[]" type="checkbox">
<input type="submit">';
?>
}
</form>

Related

Form with checkboxes getting all checked checkboxes

I am trying to make a random tournament generator, where I can select names from a list with checkboxes and then randominze them into a different order.
I have the following form:
<form method="post" action="<?php echo ROOT ?>HomeController/createTournament/" enctype="multipart/form-data">
<div class="form-group">
<label for="participants">Select participants</label><br>
<?php foreach($players as $p): ?>
<input type="checkbox" name="participants" value="<?php echo $p['name'];?>"> <?php echo $p['name'];?><br>
<?php endforeach; ?>
</div>
<button type="submit" class="btn btn-primary btn-block" name="create">Show participants</button>
</form>
This form show's a checkbox and behind the checkbox the name of the participant.
This is my method:
public function createTournament() {
if(isset($_POST["create"])) {
$participants = $_POST['participants'];
}
include('app/views/showTournament.php');
}
That means I am saving the checked ones into $participants, right?
In the file showTournament, I know have access to $partipants.
I try to var_dump $particpants and it shows me:
string(6) "Onlyoneselected name"
So I tried a foreach, to get ALL of the selected names.
<?php
foreach($participants as $p) {
echo $p;
}
;?>
The foreach isn't showing anything, but the file has access to $participants. I want all the names on my screen, so I can start randomizing them. What do I do wrong?
<input type="checkbox" name="participants"
This line here is the root of your problems.
Because every checkbox has the same name, the value of $_POST['participants'] gets overridden for each checkbox in the list.
If you change that snippet to:
<input type="checkbox" name="participants[]"
Then $_POST['participants'] becomes an array of all checked values.
You need multiple checkbox values.
And therefore, HTML name of the input should be multiple (array)
<input type="checkbox" name="participants" will return string, only latest submitted value.
<input type="checkbox" name="participants[]" will return array of all submitted values.
So, replacing name="participants" to name="participants[]" will work.

How can I collect checked items from PHP array served in form?

I have a form which builds the form items from a foreach loop and puts a checkbox by each item:
<form action="nextStep.php">
<?php
foreach ($children[0] as $myPage) {
$menuname = $info[$myPage]['label'];
echo '<input type="checkbox" id="'.$menuname.'" name="reveal_menu" value="no" unchecked><label for="'.$menuname.'">'.$menuname.'</label><br>';
}
?>
<br>
<input type="submit" value="Submit">
</form>
As you can see, I start with each item unchecked. What I would like to know is how I should build the nextStep.php script to create individual php variables that I can echo on the nextStep.php page after the user clicks the submit button?
You must identify that this input is an array of values, by appending [] on the name:
echo '<input ... name="reveal_menu[]" ...>';
In nextStep.php:
foreach($_POST['reveal_menu'] as $checkbox)
echo $checkbox;
EDIT to answer OP comment:
You would need to create an array to handle these values. But $_POST['reveal_menu'] itself is an array. So can access $_POST['reveal_menu'][0], for example.
Keep in mind that $_POST['reveal_menu'] is an array with checked values ONLY . The index 0 doesn't point for the first checkbox of your form, but for the first checkbox checked from your form.
Each item needs to have a unique value, probably the menuname, so you can tell which ones are checked, and the name needs to have [] operator appended to the end.
<form action="nextStep.php">
<?php
foreach ($children[0] as $myPage) {
$menuname = $info[$myPage]['label'];
echo '<input type="checkbox" id="'.$menuname.'" name="reveal_menu[]" value="$menuname" unchecked><label for="'.$menuname.'">'.$menuname.'</label><br>';
}
?>
<br>
<input type="submit" value="Submit">
</form>
When you loop through, you'll get an array of values.
<?php
foreach($_POST['menuname'] as $v)
{
echo($v . 'Was checked.');
}
?>

Store the array elments based on checkbox checked?

I've got this problem that I can't solve. Partly because I can't explain it with the right terms. I'm new to this so sorry for this clumsy question.
Below you can see an overview of my goal. I am displaying my check boxes in a for loop.
Here I am getting the all values in an array, but I want store the array elements based on the check box checked.
<?php
$j=0;
$arr = Array();
foreach($collection as $data) {
$mageid=$data['mageproductid'];
$products = Mage::getModel('catalog/product')->load($mageid);
$productMediaConfig = Mage::getModel('catalog/product_media_config');
$checkeven=0;
$arr[$j]=$products->getId();
//echo $arr[$j];
$j++;
} ?>
My checkbox code:
<form id="check_all" action="" method="POST" name="check" >
<input type="checkbox" class="multid[]" id="<?php echo $products->getId();?>" value="checked" /> </form>
What do I have to do in order to get checked values in my array? Did I do anything wrong?
Use input name attribute
<input type="checkbox" name="multid[<?php echo $products->getId();?>]" value="checked" />
No in you php code, check if multid[yourProductId] is set, and store them if it is set.
<?php
$j=0;
$arr = Array();
foreach($collection as $data) {
$mageid=$data['mageproductid'];
$products = Mage::getModel('catalog/product')->load($mageid);
$productMediaConfig = Mage::getModel('catalog/product_media_config');
$checkeven=0;
$arr[$j]=$products->getId();
if(!empty($_GET['multid['.$arr[$j].']']))
its checked, do something.
//echo $arr[$j];
$j++;
} ?>
After submiting the form you can get an array of checked products with $_POST['multid']
Can you use javascript? Try this one.
HTML:
<input type="hidden" id="hdnCheckedIDs" value="" />
Before submit, on submit button's client click, Javascript:
var CheckedIDs = "";
for each checkbox
if(document.getelementbyid('multid1').checked)
CheckedIDs = CheckedIDs + document.getelementbyid('multid1').id;
document.getelementbyid('checkboxID') = CheckedIDs;
In PHP, you can use this comma seperated string $_POST['hdnCheckedIDs'] to get the IDs of checked chekboxes.

Check if a field array is empty?

I want if value field txtname was empty echo It is ok but it don't work in my code(if field was empty and click on button you see output with print_r(...)), Please see my demo and my code. what do I do?
Demo: http://codepad.viper-7.com/FNWcIs
<form method="post">
<input name="txtname[]">
<button>Click Me</button>
</form>
<?php
if ($_POST) {
$txtname = $_POST['txtname'];
if (!empty($txtname)) {
echo '<pre>';
print_r($txtname); // Output this is: Array ( [0] => )
} else {
echo 'it is ok';
}
}
?>
$txtname or ($_POST['txtname']) is an array with one element. Even that element is empty, empty() returns TRUE for any array that has one or more elements.
That should explain the behavior of your code.
To achieve what you're looking for, change the HTML:
From:
<input name="txtname[]">
To:
<input name="txtname">
If you don't use the brackets, it will be a string. And empty will return FALSE if it is empty. See Variables From External Sources PHP Manual.
change input field name to txtname like show below.
<input name="txtname">
Or if you want to use array of textboxes try below code.
<form method="post">
<input name="txtname[]">
<input name="txtname[]">
<input name="txtname[]">
<button>Click Me</button>
</form>
<?php
if($_POST){
$txtname = $_POST['txtname'];
foreach($txtname as $key=>$value)
{
if(!empty($value)){
echo '<br>'.$value; // Output this is: Array ( [0] => )
}else{
echo '<br>it is ok';
}
}
}
?>
You can try it this way it works if you are not intending to pass one value to the variable $txtname
`
$txtname = $_POST['txtname'];
if($txtname[0]){
echo '<pre>';
print_r($txtname); // Output this is: Array ( [0] => )
}else{
echo 'it is ok';
}
}
?>`

Searching for Array Key in $_POST, PHP

I am trying to add commenting like StackOverflow and Facebook uses to a site I'm building. Basically, each parent post will have its own child comments. I plan to implement the front-end with jQuery Ajax but I'm struggling with how to best tackle the PHP back-end.
Since having the same name and ID for each form field would cause validation errors (and then some, probably), I added the parent post's ID to each form field. Fields that will be passed are commentID, commentBody, commentAuthor - with the ID added they will be commentTitle-12, etc.
Since the $_POST array_key will be different each time a new post is processed, I need to trim off the -12 (or whatever the ID may be) from the $_POST key, leaving just commentTitle, commentBody, etc. and its associated value.
Example
$_POST['commentTitle-12']; //how it would be received after submission
$_POST['commentTitle']; //this is what I am aiming for
Many thanks
SOLUTION
Thanks to CFreak-
//Basic example, not actual script
<?php
if (array_key_exists("send", $_POST)) {
$title = $_POST['title'][0];
$body = $_POST['body'][0];
echo $title . ', ' . $body;
}
?>
<html>
<body>
<form name="test" id="test" method="post" action="">
<input type="text" name="title[]"/>
<input type="text" name="body[]"/>
<input type="submit" name="send" id="send"/>
</form>
</body>
</html>
Update 2
Oops, kind of forgot the whole point of it - unique names (although it's been established that 1) this isn't really necessary and 2) probably better, for this application, to do this using jQuery instead)
//Basic example, not actual script
<?php
if (array_key_exists("send", $_POST)) {
$id = $_POST['id'];
$title = $_POST['title'][$id];
$body = $_POST['body'][$id];
echo $title . ', ' . $body;
}
?>
<html>
<body>
<form name="test" id="test" method="post" action="">
<input type="text" name="title[<?php echo $row['id'];?>]"/>
<input type="text" name="body[<?php echo $row['id'];?>]"/>
<input type="hidden" name="id" value="<?php echo $row['id']; //the ID?>"/>
<input type="submit" name="send" id="send"/>
</form>
</body>
</html>
PHP has a little trick to get arrays or even multi-dimensional arrays out of an HTML form. In the HTML name your field like this:
<input type="text" name="commentTitle[12]" value="(whatever default value)" />
(you can use variables or whatever to put in the "12" if that's what you're doing, the key is the [ ] brackets.
Then in PHP you'll get:
$_POST['commentTitle'][12]
You could then just loop through the comments and grabbing each by the index ID.
You can also just leave it as empty square brackets in the HTML:
<input type="text" name="commentTitle[]" value="(whatever default value)" />
That will just make it an indexed array starting at 0, if you don't care what the actual ID value is.
Hope that helps.
You just have to iterate through $_POST and search for matching keys:
function extract_vars_from_post($arr) {
$result = array();
foreach ($arr as $key => $val) {
// $key looks like asdasd-12
if (preg_match('/([a-z]+)-\d+/', $key, $match)) {
$result[$match[1]] = $val;
} else {
$result[$key] = $val;
}
}
return $result;
}
Didn't test the code, though

Categories