Essential PHP Programming: Forms, Databases, and Sessions
PHP Form Validation
To create a PHP form and perform server-side validation for user input such as name, email, and password:
<?php
$name = $email = $password = "";
$nameErr = $emailErr = $passwordErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Name Validation
if (empty($_POST["name"])) { $nameErr = "Name is required"; } else { $name = $_POST["name"]; }
// Email Validation
if (empty($_POST["email"])) { $emailErr = "Email is required"; } else { $email = $_POST["email"];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; }
}
// Password Validation
if (empty($_POST["password"])) { $passwordErr = "Password is required"; } else { $password = $_POST["password"];
if (strlen($password) < 6) { $passwordErr = "Password must be at least 6 characters"; }
}
}
?>Name:
Email: <?php echo $emailErr; ?>
Password:
MySQL Database: Inserting Multiple Records
To insert multiple records into a MySQL database table using PHP and SQL INSERT query.
Assumption
- Database name: csit_db
- Table name: students
- Fields: id, name, email
CREATE DATABASE csit_db;
USE csit_db;
CREATE TABLE students (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), email VARCHAR(50));Inheritance in PHP
Types of Inheritance in PHP:
- Single Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
PHP Cookies
A cookie is a small piece of data stored on the client's browser by a web server to maintain user information and session state.
Features of Cookies
- Stored on client browser
- Small size (around 4KB)
- Used for session tracking
- Automatically sent with HTTP request
PHP Session Handling
Sessions allow you to store user information across multiple pages.
- Start Session:
session_start(); - Destroy Session:
session_destroy();
Concatenating Strings with Functions
function joinStrings($str1, $str2) {
return $str1 . " " . $str2;
}
$result = joinStrings("ramayan", "torpey");
echo "Concatenated String: " . $result;
English with a size of 2.37 KB