Getting checkbox cell value from POST

I place an array of checkboxes. and i can't get it to work. I did not include the correct syntax in the foreach loop to make it simple. but it works. I tested trying to do the same with a text box instead of a check box, and it worked with a text box.

<form method="post"> <?php foreach{ echo' <input id="'.$userid.'" value="'.$userid.'" name="invite[]" type="checkbox"> <input type="submit">'; } ?> </form> 

here is the part that doesn't work. it repeats the "invitation" instead of an array.

 <?php if(isset($_POST['invite'])){ $invite = $_POST['invite']; echo $invite; } 
+6
source share
5 answers

The $ _POST array contains an array of prompts, so it reads like

 <?php if(isset($_POST['invite'])){ $invite = $_POST['invite']; echo $invite; } ?> 

will not work since it is an array. You need to go through the array to get all 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; } } ?> 
+20
source

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 fields, the output was:

 Array ( [0] => user1 [1] => user2 ) 

I know this does not directly answer your question, but it gives you a working example for the link and hopefully helps you solve the problem.

+11
source

Check out the implode () function as an alternative. This will convert the array to a list. The first parameter is how you want the elements to be separated. Here I used a comma with a space after it.

 $invite = implode(', ', $_POST['invite']); echo $invite; 
+5
source
 // 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]; 
0
source

Since your <form> element is inside the foreach loop, you are creating several forms. I assume that you want several checkboxes in one form.

Try it...

 <form method="post"> foreach{ <?php echo' <input id="'.$userid.'" value="'.$userid.'" name="invite[]" type="checkbox"> <input type="submit">'; ?> } </form> 
0
source

Source: https://habr.com/ru/post/916104/


All Articles