PHP Forms
In PHP, forms are used to collect data from users. Whether you are logging into a website or filling out a registration form, that data is processed on the server using PHP.
1. Form Structure
A standard HTML form contains two essential attributes: Action and Method.
- Action: This specifies the file (.php) where the data will be sent after the form is submitted.
- Method: This defines how the data is sent (either GET or POST).
<form action="submit_data.php" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
2. Purpose of the Name Attribute
To access data in PHP, the name attribute must be present inside the HTML tag. PHP identifies and retrieves the data using this specific name variable.
<!-- HTML -->
<input type="text" name="user_name">
<?php
// How to access it in PHP
$data = $_POST['user_name'];
?>
3. Form Workflow
When a user clicks the "Submit" button:
- The browser collects data from all input fields.
- The data is sent to the server via an HTTP request.
- The PHP file receives that data through Superglobals ($_GET or $_POST).
- PHP validates the data or saves it into a database.
Pro Tip: Always remember that if the form method is POST, you must use $_POST in PHP to access it. If the method is GET, use $_GET.