Form Handling1
Form Handling1
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Contact Form</h1>
</form>
</body>
</html>
<label for="name">Name:</label><br>
`for="name"`: Associates the label with the input element that has the `id="name"`.
-`required`: Ensures that the field must be filled out before submitting the form.
Email Input
<label for="email">Email:</label><br>
- Additional attributes (`id`, `name`, `required`) work similarly to the text input.
Password Input
<label for="password">Password:</label><br>
- `<input type="password">`: Creates an input field for entering a password. The characters are hidden for privacy.
Submit Button
Complete Example
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Contact Form</h1>
<label for="name">Name:</label><br>
<label for="email">Email:</label><br>
<label for="password">Password:</label><br>
</form>
</body>
</html>
PHP super global variables are built-in variables that are always accessible, regardless of scope. They provide a way
to access various types of information and to perform actions.
GET:
The GET method is one of the fundamental HTTP request methods used in web development. It is primarily
designed for requesting data from a server. In the context of HTML forms, it sends form data as part of the
URL in the form of query parameters.
Example:
Get.php
<!DOCTYPE html>
<html>
<head>
<title>GET Form Example</title>
</head>
<body>
<form action="process.php" method="get">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Explanation:
This HTML file contains a form with two input fields: one for the name and one for the email.
The form's action attribute specifies that when the form is submitted, the data will be sent to process.php.
The method attribute is set to "get", indicating that the form data will be sent as URL parameters.
Process.php
<?php
// Check if form data has been submitted
if (isset($_GET['name']) && isset($_GET['email'])) {
// Retrieve form data
$name = $_GET['name'];
$email = $_GET['email'];
// Display submitted data
echo "Name: " . $name . "<br>";
echo "Email: " . $email . "<br>";
} else {
echo "Form data not submitted.";
}
?>
Explanation:
This PHP file checks if the form data has been submitted using the GET method.
If the form data is present, it retrieves the values of 'name' and 'email' using $_GET.
It then displays the submitted data.
If the form data is not present, it outputs "Form data not submitted."
POST:
The POST method is another fundamental HTTP request method used in web development. It is primarily
designed for submitting data to a server. Unlike the GET method, which appends data to the URL, the POST
method sends data in the body of the request, making it more suitable for sending large amounts of data
and sensitive information.
Key Characteristics of the POST Method
1. Data in Request Body: Form data is sent in the body of the HTTP request.
2. Not Visible in URL:Data is not visible in the browser's address bar.
3. No Length Limit:The amount of data that can be sent is not limited by URL length restrictions.
Example:
post.php
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="process.php" method="post">
<label for="name">Name:</label>
<label for="email">Email:</label>
</form>
</body>
</html>
Explanation:
- This HTML file contains a form with two input fields: one for the name and one for the email.
- The form's `action` attribute specifies that when the form is submitted, the data will be sent to `process.php`.
- The `method` attribute is set to "post", indicating that the form data will be sent in the request body.
process.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
} else {
?>
Explanation:
- This PHP script checks if form data has been submitted using the POST method.
- It checks the `REQUEST_METHOD` server variable to determine if the request method is POST.
- If the form data is present, it retrieves the values of 'name' and 'email' using `$_POST`.
- If the form data is not present, it outputs "Form data not submitted."
`$_SERVER` is a super global variable in PHP that holds information about the server environment and the current
request. It is an associative array containing various key-value pairs with details such as server information, request
headers, file paths, and more.
$_SERVER['SERVER_NAME']: The name of the server host under which the current script is executing.
`$_REQUEST` is a super global variable in PHP that is used to collect data submitted to the server via HTML forms
with both the GET and POST methods. It merges the contents of `$_GET`, `$_POST`, and `$_COOKIE` into one array.
`$_REQUEST` collects data submitted via HTML forms regardless of the HTTP method used (GET or POST).
It combines data from `$_GET`, `$_POST`, and `$_COOKIE` arrays into one array.
While `$_REQUEST` can be convenient, it's generally not recommended to use it due to security reasons and the
ambiguity it introduces regarding the source of the data.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
?>
Form validation:
Form validation in PHP refers to the process of verifying the data submitted through an HTML form to ensure it
meets certain criteria or constraints before processing it further. This is crucial for maintaining the integrity and
security of your application's data.
1. HTML Form: You start with an HTML form where users input their data (e.g., text fields, checkboxes, radio
buttons, etc.).
2. User Input: When the user submits the form, the data is sent to a PHP script for processing.
3. PHP Validation Script: In the PHP script that receives the form data, you perform various checks on the
submitted data to ensure it's valid. This can include checks for empty fields, proper format (e.g., email
address validation), length constraints, and more.
4. Displaying Error Messages: If any validation checks fail, you typically display error messages back to the user
near the form fields where the errors occurred. This helps users understand what went wrong and how to
correct it.
5. Sanitization: Along with validation, it's also important to sanitize the data to prevent security vulnerabilities
such as SQL injection or cross-site scripting (XSS) attacks. Sanitization involves cleaning the data to remove
any potentially harmful characters.
6. Processing the Data: Once the data passes validation and sanitization, you can safely process it further, such
as saving it to a database, sending emails, etc.
Example:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate name
if (empty($_POST["name"])) {
} else {
$name = test_input($_POST["name"]);
// Validate email
if (empty($_POST["email"])) {
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Validate password
if (empty($_POST["password"])) {
} else {
$password = test_input($_POST["password"]);
if (strlen($password) < 8) {
// If name, email, and password are all valid, proceed with further processing
}
// Function to sanitize and validate input data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
?>
<span class="error"><?php echo $nameErr;?></span> <!-- Display name error message -->
<br><br>
<span class="error"><?php echo $emailErr;?></span> <!-- Display email error message -->
<br><br>
<span class="error"><?php echo $passwordErr;?></span> <!-- Display password error message -->
<br><br>
</form>
Explanation:
Variable Initialization: It initializes variables to store form input data (`$name`, `$email`, `$password`) and variables
to store error messages (`$nameErr`, `$emailErr`, `$passwordErr`).
Form Submission Check: It checks if the form has been submitted using the `$_SERVER["REQUEST_METHOD"]`
variable.
It checks if the name, email, and password fields are empty. If they are, it sets the corresponding error message
(`$nameErr`, `$emailErr`, `$passwordErr`).
If the fields are not empty, it uses the `test_input()` function to sanitize and validate the input data.
For the name, it checks if only letters and whitespace are present using a regular expression.
For the email, it uses `filter_var()` with `FILTER_VALIDATE_EMAIL` to check if it's a valid email address.
HTML Form It displays an HTML form with fields for name, email, password, and a submit button. Error messages
are displayed next to each field if there are any validation errors.
Action Attribute: The form's action attribute is set to `htmlspecialchars($_SERVER["PHP_SELF"])`, which means the
form will be submitted to the same page (`$_SERVER["PHP_SELF"]`), and `htmlspecialchars()` is used to prevent XSS
(Cross-Site Scripting) attacks by converting special characters to HTML entities.
MySQL is a popular open-source relational database management system (RDBMS) that uses Structured Query
Language (SQL) for managing and manipulating databases.
What is MySQL?
- Relational Database: It organizes data into one or more tables (relations) of rows and columns, with a unique key
identifying each row.
- SQL-based: It uses SQL (Structured Query Language) for accessing and managing data.
Basic Concepts:
-Column: A field in a table, defines the type of data stored (e.g., integer, string).
-Foreign Key: A field that links one table to another, ensuring referential integrity.
Datatypes:
1. INT (Integer)
```sql
age INT
);
sql
name VARCHAR(100)
);
3. DATE
sql
birthdate DATE
);
4. BOOLEAN
sql
is_active BOOLEAN
);
5. DECIMAL
sql
salary DECIMAL(10, 2)
);
6. TEXT
sql
description TEXT
);
INSERT INTO example_text (description) VALUES ('This is a long text description.'), ('Another description here.'),
('More text goes in this field.');
7. FLOAT
sql
value FLOAT
);
8. TIMESTAMP
Used to store date and time values, typically in 'YYYY-MM-DD HH:MM:SS' format.
sql
);
INSERT INTO example_timestamp (created_at) VALUES (NOW()), (NOW() - INTERVAL 1 DAY), (NOW() - INTERVAL 1
HOUR);