简体   繁体   中英

How do I use php $_POST to get the input from a checkbox?

So, on my form I have two input methods, a text field and a checkbox.

How would I use PHP to test if the checkbox has been checked or not? Perhaps using $_POST?

I want to check if the checkbox is checked, and if it is, set a boolean to true. I have no problems setting variables, but I can't seem to figure out how to get the input from the checkbox....

So, how would I get the input from a checkbox?

In your HTML form you have something similar:

<form method="post">
<input type="checkbox" name="vehicle" value="Bike" /> I have a bike<br />
</form>

That is a checkbox named vehicle Now, in your PHP, you would access that with:

$boolean_variable = isset( $_POST['vehicle'] );

Have a look here: http://www.homeandlearn.co.uk/php/php4p11.html

When checkboxes aren't selected, they effectively have no value, so you test it with isset .

Yes, you can using the name attribute of the input when getting the posted form values.

Here is an example:

Handling Checkbox in PHP

<input type="checkbox" name="foo" value="1" />

if (isset($_POST['foo'])) {
    // checkbox was checked
}

Checked checkboxes and their value are submitted in a POST request. Unchecked checkboxes aren't submitted. So if $_POST['foo'] exists at all, it was checked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM