How To Read If A Checkbox Is Checked In PHP? - Stack Overflow
Có thể bạn quan tâm
-
- Home
- Questions
- Tags
- Users
- Companies
- Labs
- Jobs
- Discussions
- Collectives
-
Communities for your favorite technologies. Explore all Collectives
- Teams
Ask questions, find answers and collaborate at work with Stack Overflow for Teams.
Try Teams for free Explore Teams - Teams
-
Ask questions, find answers and collaborate at work with Stack Overflow for Teams. Explore Teams
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about CollectivesTeams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about TeamsGet early access and see previews of new features.
Learn more about Labs How to read if a checkbox is checked in PHP? Ask Question Asked 13 years, 11 months ago Modified 2 years, 5 months ago Viewed 1.0m times Part of PHP Collective 320How to read if a checkbox is checked in PHP?
Share Improve this question Follow edited Feb 8, 2015 at 22:26 Thew asked Dec 29, 2010 at 14:04 ThewThew 16k19 gold badges60 silver badges102 bronze badges 1- 19 This question actually means "was checked" (when the form was submitted). PHP determining if a checkbox is checked would require an Ajax call once the element was toggled. – rybo111 Commented Jul 14, 2018 at 13:59
21 Answers
Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 410If your HTML page looks like this:
<input type="checkbox" name="test" value="value1">After submitting the form you can check it with:
isset($_POST['test'])or
if ($_POST['test'] == 'value1') ... Share Improve this answer Follow edited Oct 20, 2015 at 19:08 Andrew Thompson 169k41 gold badges222 silver badges436 bronze badges answered Dec 29, 2010 at 14:07 m_vitalym_vitaly 11.9k5 gold badges48 silver badges63 bronze badges 5- 73 Checkboxes can also have value on, when they are checked. Therefore for compatibility it's easier just to use isset($_POST['checkboxName']). – Damiqib Commented Dec 29, 2010 at 14:09
- 15 The "on" value may be supported by some browsers when value attribute is not set, but in general it is better to set the value attribute and to check for it on submit. – m_vitaly Commented Dec 29, 2010 at 14:59
- 3 Does the 'Value1' change if the box is checked? – MoralCode Commented Nov 18, 2014 at 23:08
- 15 @Developer_ACE Unless I'm misunderstanding you, the value in this example would be value1 if the checkbox is checked. If it's not checked, $_POST['test'] would simply not exist. – rybo111 Commented May 23, 2015 at 14:58
- if using serialize to submit do this. var checkbox1_data = $("#checkboxinput_id").prop("checked")==false?"0":"1"; var data = $("#formveri").serialize()+"&a="+checkbox1_data; – matasoy Commented Mar 30, 2021 at 7:00
Zend Framework use a nice hack on checkboxes, which you can also do yourself:
Every checkbox generated is associated with a hidden field of the same name, placed just before the checkbox, and with a value of "0". Then if your checkbox as the value "1", you'll always get the '0' or '1' value in the resulting GET or POST
<input type="hidden" name="foo" value="0" /> <input type="checkbox" name="foo" value="1"> Share Improve this answer Follow edited Jul 4, 2014 at 12:43 Chuck Le Butt 48.7k62 gold badges209 silver badges297 bronze badges answered Dec 29, 2010 at 15:28 regileroregilero 30.5k6 gold badges64 silver badges101 bronze badges 6- I also noticed about that, but I feel safe to use it: Zend Framework does it too! – hpaknia Commented Sep 3, 2014 at 10:49
- This is interesting. But is there a tiny possibility that the user agent might submit the first value instead of the last, assuming the checkbox is checked? – rybo111 Commented Dec 9, 2015 at 21:47
- @rybo111, for the user agent i don't think so, but for a custom javascript form parser you should take care. – regilero Commented Dec 9, 2015 at 21:52
- 12 when the checkbox is unchecked it's not transmitted in the post (so only the hidden is transmitted). When it's checked it is transmitted, and will overwrite the hidden value. – regilero Commented Feb 1, 2016 at 21:07
- 1 i really cant belive this is working. What a damn situation. Checkboxes is wrong designed so. Thank u for your answer. – matasoy Commented Mar 30, 2021 at 6:45
When using checkboxes as an array:
<input type="checkbox" name="food[]" value="Orange"> <input type="checkbox" name="food[]" value="Apple">You should use in_array():
if(in_array('Orange', $_POST['food'])){ echo 'Orange was checked!'; }Remember to check the array is set first, such as:
if(isset($_POST['food']) && in_array(... Share Improve this answer Follow edited Dec 9, 2015 at 23:49 answered Nov 4, 2013 at 16:49 rybo111rybo111 12.6k4 gold badges63 silver badges73 bronze badges 1- checkboxes as an array and foreach ($_POST['food'] as $selected_food) to work on checked one is nice, thanks – bcag2 Commented May 4, 2020 at 13:02
Let your html for your checkbox will be like
<input type="checkbox" name="check1">Then after submitting your form you need to check like
if (isset($_POST['check1'])) { // Checkbox is selected } else { // Alternate code }Assuming that check1 should be your checkbox name.And if your form submitting method is GET then you need to check with $_GET variables like
if (isset($_GET['check1'])) { // Checkbox is selected } Share Improve this answer Follow edited Sep 3, 2013 at 10:28 answered Aug 17, 2012 at 11:58 GautamD31GautamD31 28.8k10 gold badges65 silver badges86 bronze badges 0 Add a comment | 27 $check_value = isset($_POST['my_checkbox_name']) ? 1 : 0; Share Improve this answer Follow answered Apr 29, 2015 at 15:21 TheTechGuyTheTechGuy 17.3k16 gold badges119 silver badges141 bronze badges 3- 1 very fast and very clever – Tarek Kalaji Commented Jun 4, 2016 at 10:43
- 2 best solution I have seen – Debbie Kurth Commented Nov 25, 2019 at 22:51
- (int)isset($_POST['my_checkbox_name']) would do exactly the same! – csabinho Commented Nov 17, 2022 at 13:50
I've been using this trick for several years and it works perfectly without any problem for checked/unchecked checkbox status while using with PHP and Database.
HTML Code: (for Add Page)
<input name="status" type="checkbox" value="1" checked>Hint: remove checked if you want to show it as unchecked by default
HTML Code: (for Edit Page)
<input name="status" type="checkbox" value="1" <?php if ($row['status'] == 1) { echo "checked='checked'"; } ?>>PHP Code: (use for Add/Edit pages)
$status = $_POST['status']; if ($status == 1) { $status = 1; } else { $status = 0; }Hint: There will always be empty value unless user checked it. So, we already have PHP code to catch it else keep the value to 0. Then, simply use the $status variable for database.
Share Improve this answer Follow edited Mar 14, 2022 at 14:49 Brian C 8471 gold badge10 silver badges20 bronze badges answered Jul 9, 2017 at 9:47 ZEESHAN ARSHADZEESHAN ARSHAD 5765 silver badges11 bronze badges 1- 1 this is the really good form to do this in pure simple php. but have to note that the value of a checkbox is string on when it is activated an a inexisting value if it is checked. – Elvis Technologies Commented Nov 24, 2018 at 5:07
To check if a checkbox is checked use empty()
When the form is submitted, the checkbox will ALWAYS be set, because ALL POST variables will be sent with the form.
Check if checkbox is checked with empty as followed:
//Check if checkbox is checked if(!empty($_POST['checkbox'])){ #Checkbox selected code } else { #Checkbox not selected code } Share Improve this answer Follow edited Feb 9, 2019 at 11:15 ProGrammer 1,0212 gold badges14 silver badges28 bronze badges answered May 27, 2014 at 18:25 andyandy 3513 silver badges11 bronze badges 3- 5 If the checkbox is unchecked it will not be posted so it will NOW ALWAYS be set. – Wessam El Mahdy Commented Nov 15, 2018 at 9:24
- 2 ^ NOT* always be set – The Codesee Commented Jun 14, 2020 at 17:29
- @WessamElMahdy Right, that's the point of using empty(). It will check if the variable exists and is not empty without throwing an error if it doesn't exist. – Gavin Commented Sep 29, 2022 at 16:38
You can check the corresponding value as being set and non-empty in either the $_POST or $_GET array depending on your form's action.
i.e.: With a POST form using a name of "test" (i.e.: <input type="checkbox" name="test"> , you'd use:
if(isset($_POST['test']) { // The checkbox was enabled... } Share Improve this answer Follow answered Dec 29, 2010 at 14:08 John ParkerJohn Parker 54.4k11 gold badges131 silver badges130 bronze badges Add a comment | 3You can do it with the short if:
$check_value = isset($_POST['my_checkbox_name']) ? 1 : 0;or with the new PHP7 Null coalescing operator
$check_value = $_POST['my_checkbox_name'] ?? 0; Share Improve this answer Follow answered Apr 14, 2017 at 9:30 MazzMazz 1,87927 silver badges38 bronze badges Add a comment | 2Learn about isset which is a built in "function" that can be used in if statements to tell if a variable has been used or set
Example:
if(isset($_POST["testvariabel"])) { echo "testvariabel has been set!"; } Share Improve this answer Follow edited Aug 9, 2013 at 9:45 Venkateshwaran Selvaraj 1,7858 gold badges31 silver badges61 bronze badges answered Jun 4, 2013 at 20:45 user2451511user2451511 1171 gold badge1 silver badge8 bronze badges Add a comment | 2Well, the above examples work only when you want to INSERT a value, not useful for UPDATE different values to different columns, so here is my little trick to update:
//EMPTY ALL VALUES TO 0 $queryMU ='UPDATE '.$db->dbprefix().'settings SET menu_news = 0, menu_gallery = 0, menu_events = 0, menu_contact = 0'; $stmtMU = $db->prepare($queryMU); $stmtMU->execute(); if(!empty($_POST['check_menus'])) { foreach($_POST['check_menus'] as $checkU) { try { //UPDATE only the values checked $queryMU ='UPDATE '.$db->dbprefix().'settings SET '.$checkU.'= 1'; $stmtMU = $db->prepare($queryMU); $stmtMU->execute(); } catch(PDOException $e) { $msg = 'Error: ' . $e->getMessage();} } } <input type="checkbox" value="menu_news" name="check_menus[]" /> <input type="checkbox" value="menu_gallery" name="check_menus[]" />....
The secret is just update all VALUES first (in this case to 0), and since the will only send the checked values, that means everything you get should be set to 1, so everything you get set it to 1.
Example is PHP but applies for everything.
Have fun :)
Share Improve this answer Follow answered Oct 27, 2013 at 22:14 HiramHiram 2,6791 gold badge17 silver badges16 bronze badges Add a comment | 1 $is_checked = isset($_POST['your_checkbox_name']) && $_POST['your_checkbox_name'] == 'on';Short circuit evaluation will take care so that you don't access your_checkbox_name when it was not submitted.
Share Improve this answer Follow answered Jul 23, 2014 at 18:44 Martin ThomaMartin Thoma 135k172 gold badges669 silver badges1k bronze badges Add a comment | 1A minimalistic boolean check with switch position retaining
<?php $checked = ($_POST['foo'] == ' checked'); ?> <input type="checkbox" name="foo" value=" checked"<?=$_POST['foo']?>> Share Improve this answer Follow answered Feb 21, 2017 at 1:04 Rembo Rembo 112 bronze badges 2- 2 When giving an answer it is preferable to give some explanation as to WHY your answer is the one. This is especially true when answering a VERY old post 11 other answers. – Stephen Rauch ♦ Commented Feb 21, 2017 at 1:23
- It's good you recognize the need for the checkbox to retain its state. However, your code to do this is not correct. – Vern Jensen Commented Jul 5, 2017 at 20:49
- can you explain your goal here? – Elvis Technologies Commented Nov 24, 2018 at 5:09
when you check on chk2 you can see values as:
<?php foreach($_POST as $key=>$value) { if(isset($key)) $$key=strip_tags($value); } insert into table (chk1,chk2,chk3) values ('','1',''); ?> Share Improve this answer Follow edited Feb 20, 2021 at 15:51 answered Feb 20, 2021 at 15:35 Q.N.AlhalgabiQ.N.Alhalgabi 112 bronze badges Add a comment | 0in BS3 you can put
<?php $checked="hola"; $exenta = $datosOrdenCompra[0]['exenta']; var_dump($datosOrdenCompra[0]['exenta']); if(isset($datosOrdenCompra[0]['exenta']) and $datosOrdenCompra[0]['exenta'] == 1){ $checked="on"; }else{ $checked="off"; } ?> <input type="checkbox" id="exenta" name="exenta" <?php echo $checked;?> > <span class="label-text"> Exenta</span>Please Note the usage of isset($datosOrdenCompra[0]['exenta'])
Share Improve this answer Follow answered Nov 24, 2018 at 5:04 Elvis TechnologiesElvis Technologies 1518 bronze badges Add a comment | 0Wordpress have the checked() function. Reference: https://developer.wordpress.org/reference/functions/checked/
checked( mixed $checked, mixed $current = true, bool $echo = true )Description Compares the first two arguments and if identical marks as checked
Parameters $checked (mixed) (Required) One of the values to compare
$current (mixed) (Optional) (true) The other value to compare if not just true Default value: true
$echo (bool) (Optional) Whether to echo or just return the string Default value: true
Return #Return (string) html attribute or empty string
Share Improve this answer Follow answered Mar 27, 2020 at 10:12 AliquaAliqua 7287 silver badges22 bronze badges Add a comment | 0i have fixed it into a PHP form with a checkbox
$categories = get_terms( ['taxonomy' => 'product_cat', 'hide_empty' => false] ); foreach ($categories as $categorie) { echo "<input type="checkbox" value="$categorie->term_taxonomy_id" name="catselected[]"> $categorie->slug"; }
This way i add it to the Woocommerce tabel. wp_set_post_terms( $product_id, $_POST['catselected'], 'product_cat' );
Share Improve this answer Follow answered Jun 8, 2022 at 15:02 Marcel KraanMarcel Kraan 1071 silver badge9 bronze badges Add a comment | -1filter_input(INPUT_POST, 'checkbox_name', FILTER_DEFAULT, FILTER_FORCE_ARRAY)
Share Improve this answer Follow answered Jul 4, 2019 at 8:35 ThowfeekThowfeek 1371 silver badge5 bronze badges Add a comment | -3 <?php if(isset($_POST['nameCheckbox'])){ $_SESSION['fr_nameCheckbox'] = true; } ?> <input type="checkbox" name="nameCheckbox" <?php if(isset($_SESSION['fr_nameCheckbox'])){ echo 'checked'; unset($_SESSION['fr_nameCheckbox']); } ?> Share Improve this answer Follow edited Oct 21, 2016 at 13:05 rbr94 2,2773 gold badges24 silver badges40 bronze badges answered Oct 21, 2016 at 12:21 GrzegorzGrzegorz 1 1- 1 Welcome to Stack Overflow! While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please include an explanation for your code, as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Flaggers / reviewers: For code-only answers such as this one, downvote, don't delete! – Scott Weldon Commented Oct 21, 2016 at 22:54
you should give name to your input . then which box is clicked you will receive 'on' in your choose method
Array ( [shch] => on [foch] => on [ins_id] => # [ins_start] => شروع گفتگو [ins_time] => ما معمولاً در چند دقیقه پاسخ میدهیم [ins_sound] => https://.../media/sounds/ding-sound-effect_2.mp3 [ins_message] => سلام % به کمک نیاز دارید؟ [clickgen] => )i have two checked box in my form name with 'shch' and 'foch'
Share Improve this answer Follow edited May 27, 2021 at 19:36 B001ᛦ 2,0616 gold badges24 silver badges32 bronze badges answered May 27, 2021 at 8:29 taymaztaymaz 174 bronze badges Add a comment |Your Answer
Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Draft saved Draft discardedSign up or log in
Sign up using Google Sign up using Email and Password SubmitPost as a guest
Name EmailRequired, but never shown
Post Your Answer DiscardBy clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.
Not the answer you're looking for? Browse other questions tagged
or ask your own question. PHP Collective Join the discussion This question is in a collective: a subcommunity defined by tags with relevant content and experts.- The Overflow Blog
- Your docs are your infrastructure
- Featured on Meta
- More network sites to see advertising test [updated with phase 2]
- We’re (finally!) going to the cloud!
- Call for testers for an early access release of a Stack Overflow extension...
Linked
3 Get value from checkbox array through filter_input(INPUT_POST, 'check_list') -2 Using Multiple Select Boxes in HTML Form -1 PHP checkbox always returns on 0 Checkboxes issue on PHP? -1 How to change checkbox value in contact form checkbox? -1 PHP / HTML checkbox button 0 How to get checkbox value if it is not checked? 0 How would I add a check box to this PHP form 0 PHP check value of CheckBox? 0 Checkbox in PHP keeps showing False See more linked questionsRelated
0 How to judge whether <input type="checkbox" /> is checked on with PHP? 0 Determine whether a checkbox is checked upon form submission 50 How do I see which checkbox is checked? 0 PHP: Determine whether its a checkbox is checked or not 0 How do I write php code to check if checkbox is checked or not? 1 How to determine if checkbox is checked using PHP? 0 How do I find checkbox value in form sending $_POST (PHP) 0 if variable = value then tick checkbox 0 PHP Checkbox from Form 3 validate if checkbox has been checkedHot Network Questions
- How do rich people not pay inheritance taxes?
- Is there any penalty for providing half cover to another creature?
- How to protect against fake gold bars?
- Why did General Groves mention the baby delivery count here?
- Do referees get to see each other's reports?
- Can you make 5 x 3 “magic” rectangles?
- Being honest with rejection vs. "grooming" applicant for future possibility
- A novel about Earth crossing a toxic cloud of cosmic size
- Student is almost always late, and expects me to re-explain everything he missed
- Why is Anarchism not considered fundamentally against the "democratic order" in Germany?
- What is the pronunciation of these nikkud?
- Syllables of noun ‹cavalier›?
- Why is a pure copper cathode necessary in the electrolytic refining of copper?
- Can I make a pipe save data to disk instead of blocking until the reader can continue?
- Why is LM2852YMXAX-3.3 not working?
- Is the A321 XLR really necessary to fly MAD-BOS?
- How to sample a single point from a volume
- Configure Linux to regularly sync cached data to disk
- Counting of bags
- Does "bustle about" mean the same thing as "fluster about"?
- Why don't routers answer ARP requests for IP addresses they can handle even if they aren't assigned that IP address themselves?
- Publishing corollaries of previously published results
- I’m British passport Holder and my son has Italian ID can he enter UK ? Or he needs a valid passport?
- Late 70s/Early 80s android made-for-TV movie
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
defaultTừ khóa » Html Checkbox Php If Checked
-
Read If Checkbox Is Checked In PHP | Delft Stack
-
See If A Checkbox Is Checked In PHP | Beamtic
-
Get Checked Checkboxes Value With PHP - Makitweb
-
Handling Checkbox In A PHP Form Processor - HTML Form Guide
-
PHP: Get Values Of Multiple Checked Checkboxes - FormGet
-
How To Read If A Checkbox Is Checked In PHP? - GeeksforGeeks
-
How To Get Checkbox Value In Php If Checked? - Pakainfo
-
PHP Checkbox - PHP Tutorial
-
HTML Input Checked Attribute - W3Schools
-
If Checkbox Is Checked Do Something - PHP Tutorial [WordPress]
-
How To Display Text When A Checkbox Is Checked - W3Schools
-
Verifying Checkboxes Are Checked With PHP - WillMaster
-
How To Check If Checkbox Is Checked? - Laracasts
-
How To Get Checked Checkbox Value In Php? - Lotus