0% found this document useful (0 votes)
23 views13 pages

Form Handling1

Uploaded by

vishalap775
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views13 pages

Form Handling1

Uploaded by

vishalap775
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Form Handling

Creating a simple html form

Basic HTML Form Structure

<!DOCTYPE html>

<html>

<head>

<title>Simple HTML Form</title>

</head>

<body>

<h1>Contact Form</h1>

<form action="/submit_form" method="post">

<!-- Form Fields Go Here -->

</form>

</body>

</html>

Text Input for Name

<label for="name">Name:</label><br>

<input type="text" id="name" name="name" required><br><br>

<label>: Defines a label for an input element.

`for="name"`: Associates the label with the input element that has the `id="name"`.

`<input type="text">`: Creates a single-line text input field.

`id="name": Uniquely identifies the input field.

`name="name": Names the input field for form submission.

-`required`: Ensures that the field must be filled out before submitting the form.

Email Input

<!-- Email input -->

<label for="email">Email:</label><br>

<input type="email" id="email" name="email" required><br><br>

`<input type="email">`: Creates an input field for entering an email address.

- Additional attributes (`id`, `name`, `required`) work similarly to the text input.
Password Input

<!-- Password input -->

<label for="password">Password:</label><br>

<input type="password" id="password" name="password" required><br><br>

- `<input type="password">`: Creates an input field for entering a password. The characters are hidden for privacy.

- Similar attributes (`id`, `name`, `required`) as above.

Submit Button

<!-- Submit button -->

<input type="submit" value="Submit">

`<input type="submit">`: Creates a button to submit the form.

`value="Submit"`: Sets the text on the button.

Complete Example

Here’s the complete form with all the fields together:

<!DOCTYPE html>

<html>

<head>

<title>Simple HTML Form</title>

</head>

<body>

<h1>Contact Form</h1>

<form action="/submit_form" method="post">

<!-- Text input for name -->

<label for="name">Name:</label><br>

<input type="text" id="name" name="name" required><br><br>

<!-- Email input -->

<label for="email">Email:</label><br>

<input type="email" id="email" name="email" required><br><br>

<!-- Password input -->

<label for="password">Password:</label><br>

<input type="password" id="password" name="password" required><br><br>

<!-- Submit button -->


<input type="submit" value="Submit">

</form>

</body>

</html>

Super Global Variables:

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: Collects data sent in the URL query string.


 $_POST: Collects data sent in the HTTP POST request.
 $_SERVER: Holds information about headers, paths, and script locations.
 $_REQUEST: Collects data from both $_GET and $_POST.

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.

Key Characteristics of the GET Method

1. URL Parameters: Data is appended to the URL as query parameters.


2. Data Length: Limited by the maximum URL length Limited Data Size The amount of data that can be sent
is limited by URL length restrictions.
3. Data Visibility: Data is visible in the URL, which is not suitable for sensitive information like passwords.

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>

<title>POST Form Example</title>

</head>

<body>
<form action="process.php" method="post">

<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 "post", indicating that the form data will be sent in the request body.

process.php

<?php

// Check if form data has been submitted

if ($_SERVER["REQUEST_METHOD"] == "POST") {

// Retrieve form data

$name = $_POST['name'];

$email = $_POST['email'];

// Display submitted data

echo "Name: " . $name . "<br>";

echo "Email: " . $email . "<br>";

} else {

echo "Form data not submitted.";

?>
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`.

- It then displays the submitted data.

- 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.

Here are some common elements of `$_SERVER`:

$_SERVER['PHP_SELF']: Contains the filename of the currently executing script.

$_SERVER['SERVER_NAME']: The name of the server host under which the current script is executing.

$_SERVER['REQUEST_METHOD']: The request method used to access the page

$_SERVER['SCRIPT_FILENAME']: The absolute pathname of the currently executing script.

$_SERVER['SCRIPT_NAME']: Contains the path of the current script.

`$_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.

Here's a basic example of how `$_REQUEST` is used:

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$name = $_REQUEST['name']; // Assuming 'name' is submitted via either GET or POST

// Process the data...

?>
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.

Here's a basic overview of how form validation typically works in PHP:

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

// Define variables and initialize with empty values

$name = $email = $password = "";

$nameErr = $emailErr = $passwordErr = "";

// Check if the form is submitted

if ($_SERVER["REQUEST_METHOD"] == "POST") {

// Validate name

if (empty($_POST["name"])) {

$nameErr = "Name is required";

} else {

$name = test_input($_POST["name"]);

// Check if name only contains letters and whitespace

if (!preg_match("/^[a-zA-Z ]*$/", $name)) {

$nameErr = "Only letters and white space allowed";


}

// Validate email

if (empty($_POST["email"])) {

$emailErr = "Email is required";

} else {

$email = test_input($_POST["email"]);

// Check if email address is valid

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

$emailErr = "Invalid email format";

// Validate password

if (empty($_POST["password"])) {

$passwordErr = "Password is required";

} else {

$password = test_input($_POST["password"]);

// Check if password meets certain criteria (e.g., minimum length)

if (strlen($password) < 8) {

$passwordErr = "Password must be at least 8 characters long";

// If name, email, and password are all valid, proceed with further processing

if (empty($nameErr) && empty($emailErr) && empty($passwordErr)) {

// Further processing, e.g., saving to database or sending email

}
// Function to sanitize and validate input data

function test_input($data) {

$data = trim($data);

$data = stripslashes($data);

$data = htmlspecialchars($data);

return $data;

?>

<!-- HTML Form -->

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">

Name: <input type="text" name="name">

<span class="error"><?php echo $nameErr;?></span> <!-- Display name error message -->

<br><br>

Email: <input type="text" name="email">

<span class="error"><?php echo $emailErr;?></span> <!-- Display email error message -->

<br><br>

Password: <input type="password" name="password">

<span class="error"><?php echo $passwordErr;?></span> <!-- Display password error message -->

<br><br>

<input type="submit" name="submit" value="Submit">

</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.

Validation of Name, Email, and Password:

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.

For the password, it checks if its length is at least 8 characters.

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?

MySQL is free to use, with an option for commercial licensing.

- 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:

-Database: A collection of related tables.

-Table: A collection of related data entries, consisting of rows and columns.

-Row: A single record in a table.

-Column: A field in a table, defines the type of data stored (e.g., integer, string).

-Primary Key: A unique identifier for a row in a table.

-Foreign Key: A field that links one table to another, ensuring referential integrity.
Datatypes:

1. INT (Integer)

Used to store whole numbers.

```sql

CREATE TABLE example_int (

id INT AUTO_INCREMENT PRIMARY KEY,

age INT

);

INSERT INTO example_int (age) VALUES (25), (30), (45);

2. VARCHAR (Variable Character)

Used to store variable-length strings.

sql

CREATE TABLE example_varchar (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(100)

);

INSERT INTO example_varchar (name) VALUES ('Alice'), ('Bob'), ('Charlie');

3. DATE

Used to store dates in the format 'YYYY-MM-DD'.

sql

CREATE TABLE example_date (

id INT AUTO_INCREMENT PRIMARY KEY,

birthdate DATE

);

INSERT INTO example_date (birthdate) VALUES ('1990-01-01'), ('1985-05-20'), ('2000-12-15');

4. BOOLEAN

Used to store true/false values.

sql

CREATE TABLE example_boolean (

id INT AUTO_INCREMENT PRIMARY KEY,

is_active BOOLEAN
);

INSERT INTO example_boolean (is_active) VALUES (TRUE), (FALSE), (TRUE);

5. DECIMAL

Used to store fixed-point numbers, suitable for storing monetary values.

sql

CREATE TABLE example_decimal (

id INT AUTO_INCREMENT PRIMARY KEY,

salary DECIMAL(10, 2)

);

INSERT INTO example_decimal (salary) VALUES (50000.00), (60000.50), (45000.75);

6. TEXT

Used to store large amounts of text.

sql

CREATE TABLE example_text (

id INT AUTO_INCREMENT PRIMARY KEY,

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

Used to store floating-point numbers.

sql

CREATE TABLE example_float (

id INT AUTO_INCREMENT PRIMARY KEY,

value FLOAT

);

INSERT INTO example_float (value) VALUES (123.45), (678.90), (12.34);

8. TIMESTAMP

Used to store date and time values, typically in 'YYYY-MM-DD HH:MM:SS' format.

sql

CREATE TABLE example_timestamp (

id INT AUTO_INCREMENT PRIMARY KEY,


created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

);

INSERT INTO example_timestamp (created_at) VALUES (NOW()), (NOW() - INTERVAL 1 DAY), (NOW() - INTERVAL 1
HOUR);

You might also like