PHP Introduction | Form Submission Basics | Using Other Form Elements
Now that we understand the basics of using forms, let us also look at how to use other elements.
In addition to input fields, forms have elements such as “checkboxes,” “radio buttons,” “lists,” “text areas,” and “password fields.” Text areas and password fields send text in the same way as the input fields used earlier, so their usage is easy to understand because you only receive the characters that were sent.
Then how do checkboxes and radio buttons pass values? Let us actually try it.
Look at the following form example, which displays a checkbox, two radio buttons, and a list with three items.
<?php
if ($_POST != null){
$ck1 =$_POST['check1'];
$rd1 = $_POST['radio1'];
$sl1 = $_POST['list1'];
$result = "CHECKBOX: {$ck1}\nRADIOBUTTON: {$rd1}\nSELECT: {$sl1}";
} else {
$result = "Please enter a value.";
}
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8" />
<title>sample page</title>
</head>
<body>
<h1>Hello PHP!</h1>
<pre><?php
echo htmlspecialchars($result);
?></pre>
<form method="post" action="./index.php">
<input type="checkbox" name="check1">Checkbox<br>
<input type="radio" name="radio1" value="Selected number 1">Radio button 1<br>
<input type="radio" name="radio1" value="Selected number 2">Radio button 2<br>
<select name="list1">
<option value="Windows">Windows</option>
<option value="Mac OS">Mac OS</option>
<option value="Linux">Linux</option>
</select>
<input type="submit">
</form>
</body>
</html>
Run this and check how each value is passed.
Checkbox
If the checkbox is ON, it sends the value "on". What happens if it is OFF? It sends nothing. In other words, the value is empty.
Radio Buttons
The value of the selected radio button’s value attribute is sent. If value is not set, it only sends "on", just like a checkbox. Since that would not tell you which radio button was selected, be sure to write a value.
Also, if no radio button is selected, nothing is sent, just like with a checkbox.
Lists
<select> can be displayed like a combo box or like a list, but the value that is sent is the same in either case. The value of the selected <option> is sent. If value is not set, the text written between <option> and </option> is sent.
Also, if nothing is selected, nothing is sent.