R
Rishtaara
Knowledge Hub
Technology & IT

PHP Fundamentals: Web Development Notes

By Rishtaara Editorial Team110 min read
#PHP#MySQL#Web#Backend#OOP

Full PHP syllabus — syntax, forms, OOP, sessions, MySQL, XML, and AJAX with real-life examples and copy-paste code.

PHP HOME — what this course covers

This Rishtaara PHP course teaches you step by step — from your first echo to MySQL, OOP, and AJAX.

PHP (PHP: Hypertext Preprocessor) runs on the server. It builds HTML pages, talks to databases, handles forms, and powers sites like WordPress and Laravel apps.

Real-life example: Learning PHP is like learning to cook in a restaurant kitchen. HTML/CSS set the table. PHP prepares the meal before guests arrive.

  • Basics: syntax, variables, loops, functions, arrays
  • Forms, validation, sessions, and file handling
  • OOP: classes, inheritance, interfaces, traits
  • MySQL, XML, AJAX, and real project patterns
Tip: Install XAMPP or use Docker with PHP + Apache + MySQL. Save files as .php and open them through localhost, not as file://.

Introduction — what is PHP?

PHP is a server-side scripting language. The browser never sees your PHP source code — only the HTML output PHP sends back.

PHP can read form data, save to MySQL, send emails, create files, and return JSON for mobile apps.

Real-life example: PHP is like a waiter. The customer (browser) orders food. The waiter (PHP) goes to the kitchen (server + database) and brings back the finished plate (HTML/JSON).

  • Runs on Apache, Nginx, and built-in PHP server
  • Works with MySQL, PostgreSQL, SQLite, and more
  • Free, open source, huge community and job market
HTTP request cycle

PHP vs HTML — who does what?

HTML describes page structure. CSS styles it. JavaScript runs in the browser. PHP runs on the server before the page is sent.

A .php file can mix HTML and PHP tags. The server processes <?php ... ?> blocks and sends plain HTML to the browser.

Real-life example: HTML is the menu card. PHP is the chef who reads orders and writes today's specials on the board.

Mixed HTML and PHP
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Rishtaara PHP</title>
</head>
<body>
  <h1><?php echo "Welcome to Rishtaara!"; ?></h1>
  <p>Today is <?php echo date("l, F j, Y"); ?>.</p>
</body>
</html>

Install PHP — local setup

Install XAMPP (Windows/Mac/Linux) or use Homebrew: brew install php. Start Apache and MySQL from the XAMPP control panel.

Save files in htdocs (e.g. htdocs/knowvora/index.php) and visit http://localhost/knowvora/index.php.

Real-life example: Installing PHP is like setting up a workshop. XAMPP gives you the tools (PHP, Apache, MySQL) on one workbench.

  • Check version: php -v in terminal
  • Built-in server: php -S localhost:8000
  • Use VS Code with PHP Intelephense extension
Verify PHP works
<?php
// Save as index.php and open via localhost
phpinfo(); // Shows PHP version and modules — remove in production!
?>

PHP Syntax

PHP scripts start with <?php and end with ?>. Statements end with a semicolon (;). PHP is not case-sensitive for keywords but is case-sensitive for variables.

Real-life example: Semicolons are like periods at the end of sentences. Without them, PHP gets confused about where one instruction ends.

Basic syntax rules
<?php
// PHP block must start with <?php
echo "Hello, Rishtaara!"; // semicolon required

// Wrong: echo "Hi" (missing semicolon)
?>

Comments

Use // for single-line comments and /* ... */ for multi-line blocks. Comments help humans; PHP ignores them.

Real-life example: Comments are pencil notes in your notebook margin — they remind you why you wrote code, but the teacher skips them.

Single-line and multi-line comments
<?php
// This line is a comment
$course = "PHP Fundamentals"; // inline comment

/*
  Multi-line comment
  for longer explanations
*/
echo $course;
?>

Variables

Variables store data. Names start with $ and are case-sensitive. PHP creates variables when you assign a value — no let or var keyword.

Real-life example: A variable is a labeled box. $name holds "Asha" today; tomorrow you can put "Ravi" in the same box.

Creating and using variables
<?php
$name = "Asha";
$age = 22;
$price = 1999.50;
$isStudent = true;

echo "Name: $name, Age: $age";
?>

Echo

echo is the most common way to output text. It accepts multiple comma-separated strings and works inside double-quoted strings with variables.

Real-life example: echo is a loudspeaker — you announce text to the page visitor.

Echo examples
<?php
$course = "PHP";
echo "Learning ", $course, " on Rishtaara!";
echo "<br>Line two";
?>

Print

print is like echo but returns 1 and accepts only one argument. Most developers prefer echo because it is slightly faster and more flexible.

Real-life example: print is a single-page flyer. echo is a stack of flyers — you can hand out many at once.

Print vs echo
<?php
$msg = "Hello from Rishtaara";
print $msg;   // returns 1
echo $msg;    // preferred in most code
?>

Data Types

PHP supports string, integer, float, boolean, array, object, NULL, and resource types. Variables are loosely typed — type can change on reassignment.

Real-life example: Data types are container shapes — a string holds words, an integer holds whole counts, a float holds prices with decimals.

Common data types
<?php
$text = "Rishtaara";     // string
$count = 32;            // integer
$rating = 4.8;          // float
$active = true;         // boolean
$empty = null;          // NULL

var_dump($text, $count, $rating, $active, $empty);
?>

Strings

Use single quotes for plain text and double quotes when you need variable interpolation or escape sequences like \n.

Real-life example: Single quotes are a plain white T-shirt. Double quotes are a T-shirt with your name printed on it.

String quotes and concatenation
<?php
$first = "Asha";
$last = "Khan";

// Concatenation with .
$full = $first . " " . $last;

// Double quotes interpolate variables
echo "Hello, $full";

// Useful string functions
echo strlen($full);       // length
echo strtoupper($first);  // ASHA
?>

Numbers — Integers and Floats

Integers are whole numbers. Floats (doubles) have decimal points. PHP automatically picks the type from how you write the value.

Real-life example: Integers count whole apples. Floats measure weight when you need grams and decimals.

Integer and float operations
<?php
$lessons = 32;
$hours = 10.5;
$totalMinutes = $lessons * 30 + $hours * 60;

echo "Total study minutes: $totalMinutes";
echo is_int($lessons) ? " lessons is int" : "";
echo is_float($hours) ? " hours is float" : "";
?>

Type Casting

Casting converts one type to another. Use (int), (float), (string), (bool), or functions like intval(), floatval(), strval().

Real-life example: Casting is pouring juice from a big bottle into a small cup — same liquid, different container shape.

Casting examples
<?php
$price = "1999.50";
$intPrice = (int) $price;      // 1999
$floatPrice = (float) $price;  // 1999.5
$strCount = (string) 32;       // "32"

echo $intPrice, " ", $floatPrice, " ", $strCount;
?>

Math

PHP supports +, -, *, /, % (modulo), and ** (power). Use abs(), round(), ceil(), floor(), min(), max(), and rand() for common tasks.

Real-life example: Math in PHP is a calculator on the server — discount prices, split bills, or pick a random quiz question.

Math operators and functions
<?php
$a = 10;
$b = 3;

echo $a + $b;           // 13
echo $a % $b;           // 1 (remainder)
echo $a ** $b;          // 1000 (power)

echo round(4.567, 2);   // 4.57
echo rand(1, 10);       // random 1–10
?>

Constants

Constants hold values that never change. Define them with define('NAME', value) or const NAME = value inside classes.

Real-life example: A constant is the speed limit on a road — everyone reads the same number; it does not change mid-drive.

define() and const
<?php
define("SITE_NAME", "Rishtaara");
define("MAX_LOGIN_ATTEMPTS", 5);

const COURSE_SLUG = "php-fundamentals";

echo SITE_NAME . " — " . COURSE_SLUG;
?>

Magic Constants

Magic constants are built-in placeholders that change depending on where they appear: __LINE__, __FILE__, __DIR__, __FUNCTION__, __CLASS__, __METHOD__, __NAMESPACE__.

Real-life example: Magic constants are like automatic name tags at a conference — they always show your current booth, room, or session.

Magic constant examples
<?php
function showDebugInfo() {
  echo "Function: " . __FUNCTION__ . "\n";
  echo "Line: " . __LINE__ . "\n";
  echo "File: " . __FILE__;
}
showDebugInfo();
?>

Operators — arithmetic and assignment

Use +=, -=, *=, /= for shorthand assignment. The concatenation operator . joins strings.

Real-life example: += is adding more coins to a piggy bank without counting the old total first.

Assignment and concatenation
<?php
$score = 10;
$score += 5;  // 15

$greeting = "Hello";
$greeting .= ", Rishtaara!"; // "Hello, Rishtaara!"
echo $greeting;
?>

Comparison and logical operators

Compare with ==, ===, !=, !==, <, >, <=, >=. Combine conditions with &&, ||, and !. Prefer === to avoid type surprises.

Real-life example: === checks both the gift and the wrapping paper match. == only checks if the gift looks similar.

Comparisons and logic
<?php
$age = 18;
$hasId = true;

if ($age >= 18 && $hasId) {
  echo "Entry allowed";
}

// Strict vs loose
var_dump(0 == "");   // true (loose)
var_dump(0 === "");  // false (strict)
?>

If...Else

Use if, else if, and else to run code only when conditions are true. Curly braces { } group multiple statements.

Real-life example: If it rains, take an umbrella. Else if it is sunny, wear a hat. Else stay inside.

if / elseif / else
<?php
$score = 82;

if ($score >= 90) {
  echo "Grade A";
} elseif ($score >= 75) {
  echo "Grade B";
} else {
  echo "Keep practicing on Rishtaara";
}
?>

Switch

switch compares one value against many cases. Use break to stop fall-through. default runs when nothing matches.

Real-life example: A switch is a vending machine keypad — press B3 for chips, B4 for cookies, default says "invalid choice."

switch statement
<?php
$day = "Mon";

switch ($day) {
  case "Mon":
    echo "Start of week";
    break;
  case "Fri":
    echo "Almost weekend";
    break;
  default:
    echo "Regular day";
}
?>

Match (PHP 8+)

match is a stricter, cleaner alternative to switch. It returns a value, uses === comparison, and throws if no arm matches (unless default is used).

Real-life example: match is a smart elevator — you pick floor 3 and it goes exactly there, no stopping at wrong floors.

match expression
<?php
$status = 404;

$message = match ($status) {
  200 => "OK",
  404 => "Page not found",
  500 => "Server error",
  default => "Unknown status",
};

echo $message;
?>

While and Do...While

while repeats while a condition is true. do...while runs the body at least once, then checks the condition.

Real-life example: while is "keep filling cups while water remains." do...while is "serve one cup, then check if more guests want water."

while and do...while
<?php
$i = 1;
while ($i <= 3) {
  echo "Lesson $i\n";
  $i++;
}

$j = 1;
do {
  echo "At least once: $j\n";
  $j++;
} while ($j <= 1);
?>

For loop

for(init; condition; increment) is ideal when you know how many times to repeat — like looping lesson numbers 1 to 32.

Real-life example: A for loop is climbing stairs — start at step 1, stop at step 10, go up one each time.

for loop
<?php
for ($lesson = 1; $lesson <= 5; $lesson++) {
  echo "PHP Lesson $lesson\n";
}

// Nested loop — multiplication table row
for ($x = 1; $x <= 3; $x++) {
  for ($y = 1; $y <= 3; $y++) {
    echo "$x x $y = " . ($x * $y) . "\n";
  }
}
?>

Foreach — looping arrays

foreach walks through every item in an array. Use as $value or as $key => $value for associative arrays.

Real-life example: foreach is reading every name on a class attendance sheet one by one.

foreach examples
<?php
$topics = ["Syntax", "Forms", "MySQL", "OOP"];

foreach ($topics as $topic) {
  echo "- $topic\n";
}

$user = ["name" => "Asha", "role" => "student"];
foreach ($user as $key => $value) {
  echo "$key: $value\n";
}
?>

Break and Continue

break exits the loop early. continue skips the rest of the current iteration and moves to the next one.

Real-life example: break is leaving the queue when you find your friend. continue is skipping one bad apple and checking the next.

break and continue
<?php
for ($i = 1; $i <= 10; $i++) {
  if ($i === 5) continue; // skip 5
  if ($i === 8) break;    // stop at 8
  echo "$i ";
}
?>

User-defined functions

Functions group reusable code. Define with function name() { }. Pass parameters and use return to send a value back.

Real-life example: A function is a recipe card — write it once, cook the dish whenever you need it.

Basic function
<?php
function greet(string $name): string {
  return "Hello, $name!";
}

echo greet("Asha");

function add(int $a, int $b): int {
  return $a + $b;
}
echo add(3, 5); // 8
?>

Default parameters and type hints

Parameters can have default values. PHP 7+ supports scalar type hints and return types for safer code.

Real-life example: Default parameters are a coffee shop asking "regular milk?" — you only speak up when you want something different.

Defaults and types
<?php
function calculateDiscount(float $price, float $percent = 10): float {
  return $price - ($price * $percent / 100);
}

echo calculateDiscount(2000);      // 10% default
echo calculateDiscount(2000, 20);    // 20%
?>

Variable scope

Variables inside a function are local. Use global $name inside a function or pass values as arguments. Avoid global when possible.

Real-life example: Local scope is a private diary in your room. Global is a family notice board everyone can read.

Local vs global
<?php
$site = "Rishtaara";

function showSite(): void {
  global $site; // prefer passing as parameter instead
  echo $site;
}
showSite();
?>

Indexed arrays

Indexed arrays store lists with numeric keys starting at 0. Create with array() or short syntax [].

Real-life example: An indexed array is a numbered locker row — locker 0, locker 1, locker 2.

Indexed array
<?php
$courses = ["HTML", "CSS", "PHP", "MySQL"];
echo $courses[0]; // HTML
echo count($courses); // 4

$courses[] = "JavaScript"; // append
?>

Associative arrays

Associative arrays use named keys instead of numbers — perfect for user records and config settings.

Real-life example: Associative arrays are labeled drawers — "socks", "shirts", "pants" instead of drawer 1, 2, 3.

Associative array
<?php
$user = [
  "id" => 101,
  "name" => "Asha",
  "email" => "asha@example.com",
  "role" => "student"
];

echo $user["name"];
foreach ($user as $key => $val) {
  echo "$key: $val\n";
}
?>

Multidimensional arrays

Arrays can contain other arrays — useful for tables of students, products, or quiz questions.

Real-life example: A spreadsheet is a 2D array — rows and columns of data.

2D array
<?php
$students = [
  ["name" => "Asha", "score" => 88],
  ["name" => "Ravi", "score" => 92],
];

echo $students[1]["name"]; // Ravi

// Useful array functions
$nums = [3, 1, 4, 1, 5];
sort($nums);
print_r($nums);
?>

What are superglobals?

Superglobals are built-in arrays available everywhere in your script. They carry request data, server info, cookies, files, and session state.

Real-life example: Superglobals are airport baggage tags — every handler along the way can read the same tag without you passing bags manually.

  • $_GET — data from URL query string (?id=5)
  • $_POST — form data sent with POST method
  • $_REQUEST — GET + POST + COOKIE (avoid for clarity)
  • $_SERVER — headers, method, script path
  • $_COOKIE — browser cookies
  • $_SESSION — server-side session data
  • $_FILES — uploaded file metadata
  • $_ENV — environment variables

$_GET and $_POST

Use $_GET for search filters and page IDs. Use $_POST for login forms and data that should not sit in the URL. Always validate and sanitize.

Real-life example: $_GET is shouting your order across the room. $_POST is handing a sealed envelope to the cashier.

Reading GET and POST safely
<?php
// URL: page.php?id=5
$id = filter_input(INPUT_GET, "id", FILTER_VALIDATE_INT);

if ($_SERVER["REQUEST_METHOD"] === "POST") {
  $name = trim($_POST["name"] ?? "");
  if ($name !== "") {
    echo "Hello, " . htmlspecialchars($name);
  }
}
?>

$_SERVER and $_FILES overview

$_SERVER['REQUEST_METHOD'] tells GET or POST. $_SERVER['HTTP_USER_AGENT'] shows browser info. $_FILES holds upload temp paths and sizes.

Real-life example: $_SERVER is the receipt printer at checkout — it records time, register number, and payment method.

Useful $_SERVER keys
<?php
echo $_SERVER["REQUEST_METHOD"];
echo $_SERVER["PHP_SELF"];
echo $_SERVER["HTTP_HOST"];

// After file upload form:
// $_FILES["photo"]["name"], ["tmp_name"], ["size"], ["error"]
?>

Regular Expressions — pattern matching

RegEx finds patterns in strings — emails, phone numbers, passwords. PHP wraps patterns in delimiters like /pattern/.

Real-life example: RegEx is a bouncer with a dress code list — only strings matching the pattern get in.

Basic pattern
<?php
$text = "Contact: asha@knowvora.com";

// preg_match — find first match
if (preg_match("/[a-z]+@[a-z]+\.[a-z]+/i", $text, $matches)) {
  echo "Found email: " . $matches[0];
}
?>

Common RegEx functions

preg_match() checks if pattern exists. preg_match_all() finds all matches. preg_replace() swaps matched text. preg_split() splits by pattern.

Real-life example: preg_replace is find-and-replace in Word. preg_split is cutting a rope wherever you see a knot.

preg_match, preg_replace, preg_split
<?php
$phone = "Call 98765-43210 today";

// Replace digits with X
$masked = preg_replace("/\d/", "X", $phone);
echo $masked;

// Split by comma or space
$tags = "php, mysql ajax";
$parts = preg_split("/[,\s]+/", $tags);
print_r($parts);
?>

Validation with RegEx

Use RegEx for format checks but prefer filter_var() for emails and URLs when possible — it is simpler and well tested.

Real-life example: Checking password strength with RegEx is like a gym trainer — at least 8 chars, one number, one symbol.

Password pattern check
<?php
$password = "Rishtaara1!";

$strong = preg_match(
  "/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/",
  $password
);

echo $strong ? "Strong password" : "Weak password";
?>

PHP Form Handling

HTML forms send data to PHP using method="get" or method="post" and action="process.php". PHP reads fields from $_GET or $_POST.

Real-life example: A form is an order slip. The customer fills it; PHP is the kitchen that reads the slip and cooks the response.

HTML form + PHP handler
<!-- register.html -->
<form method="post" action="register.php">
  <label>Name: <input type="text" name="name" required /></label>
  <label>Email: <input type="email" name="email" required /></label>
  <button type="submit">Register</button>
</form>
register.php
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
  $name = trim($_POST["name"] ?? "");
  $email = trim($_POST["email"] ?? "");
  echo "Registered: " . htmlspecialchars($name) . " ($email)";
}
?>

Form Validation

Never trust user input. Check empty fields, correct formats, and length limits on the server — browser validation can be bypassed.

Real-life example: Validation is a security guard checking IDs at the door — friendly, but firm.

Server-side validation
<?php
$errors = [];

if ($_SERVER["REQUEST_METHOD"] === "POST") {
  $name = trim($_POST["name"] ?? "");
  if ($name === "") {
    $errors[] = "Name is required.";
  } elseif (strlen($name) < 2) {
    $errors[] = "Name must be at least 2 characters.";
  }

  if ($errors) {
    foreach ($errors as $e) echo "<p style='color:red'>$e</p>";
  } else {
    echo "Valid submission!";
  }
}
?>

Required Fields

Use HTML required attribute for quick feedback, but always re-check on the server with empty() or trim() === "".

Real-life example: Required fields are mandatory questions on an exam — blank answers mean no pass.

Required check in PHP
<?php
function required(string $value, string $label): ?string {
  if (trim($value) === "") {
    return "$label is required.";
  }
  return null;
}

$error = required($_POST["course"] ?? "", "Course name");
echo $error ?? "OK";
?>

Validate URL and Email

filter_var() with FILTER_VALIDATE_EMAIL and FILTER_VALIDATE_URL is the safest easy check for common formats.

Real-life example: Email validation is checking if an address looks like a real mailbox, not random keyboard smashes.

filter_var validation
<?php
$email = "asha@knowvora.com";
$url = "https://knowvora.com";

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo "Invalid email";
}

if (!filter_var($url, FILTER_VALIDATE_URL)) {
  echo "Invalid URL";
}
?>

Complete Form Example

A complete form shows errors, keeps old values, and escapes output with htmlspecialchars() to prevent XSS attacks.

Real-life example: A complete form is a polite reception desk — it tells you what went wrong and remembers what you already typed.

Full contact form (single file)
<?php
$name = $email = $message = "";
$errors = [];

if ($_SERVER["REQUEST_METHOD"] === "POST") {
  $name = trim($_POST["name"] ?? "");
  $email = trim($_POST["email"] ?? "");
  $message = trim($_POST["message"] ?? "");

  if ($name === "") $errors[] = "Name required.";
  if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Valid email required.";
  if ($message === "") $errors[] = "Message required.";

  if (!$errors) {
    echo "<p>Thanks, " . htmlspecialchars($name) . "! We will reply soon.</p>";
  }
}
?>
<form method="post">
  <input name="name" value="<?= htmlspecialchars($name) ?>" placeholder="Name" />
  <input name="email" value="<?= htmlspecialchars($email) ?>" placeholder="Email" />
  <textarea name="message"><?= htmlspecialchars($message) ?></textarea>
  <button type="submit">Send</button>
</form>
<?php foreach ($errors as $e): ?>
  <p style="color:red"><?= htmlspecialchars($e) ?></p>
<?php endforeach; ?>

Date and Time

Use date() for formatted output and time() for Unix timestamps. DateTime class gives object-oriented date handling.

Real-life example: date() is a wall clock you can reformat — show 24-hour time, month names, or ISO dates.

date() and DateTime
<?php
echo date("Y-m-d H:i:s"); // 2026-07-24 10:30:00
echo date("l, F j, Y");   // Thursday, July 24, 2026

$dt = new DateTime("now", new DateTimeZone("Asia/Kolkata"));
$dt->modify("+7 days");
echo $dt->format("Y-m-d");
?>

Include and Require

include and require pull other PHP files into the current script. require stops with fatal error if missing; include only warns.

Use include_once / require_once to avoid loading the same file twice.

Real-life example: include is copying a shared recipe into tonight's menu — header.php on every page.

header.php and footer.php pattern
<?php
// index.php
$pageTitle = "Rishtaara PHP Course";
require "header.php";
?>

<main>
  <h1>Welcome to Rishtaara</h1>
</main>

<?php require "footer.php"; ?>
header.php
<!DOCTYPE html>
<html lang="en">
<head>
  <title><?= htmlspecialchars($pageTitle ?? "Site") ?></title>
</head>
<body>

Open and Read Files

fopen() opens a file. fread() or fgets() reads content. file_get_contents() is a shortcut for small files. Always fclose() when done.

Real-life example: Reading a file is opening a notebook and copying notes into your working memory.

Read a text file
<?php
$path = "notes.txt";

// Shortcut
$content = file_get_contents($path);
echo $content;

// Line by line
$handle = fopen($path, "r");
while (($line = fgets($handle)) !== false) {
  echo trim($line) . "\n";
}
fclose($handle);
?>

Create and Write Files

Use fopen($path, 'w') to create/overwrite or 'a' to append. file_put_contents() is simpler for quick writes.

Real-life example: Writing a file is saving a diary entry — new page (w) or add to today's page (a).

Write and append
<?php
$log = "User logged in at " . date("H:i:s") . "\n";

// Append to log file
file_put_contents("app.log", $log, FILE_APPEND);

// Overwrite
file_put_contents("config.txt", "debug=false");
?>

File existence and permissions

Check file_exists(), is_readable(), and is_writable() before operations. Handle errors when folders are missing.

Real-life example: Checking permissions is knocking before entering a room — polite and prevents crashes.

Safe file check
<?php
$file = "data.json";

if (file_exists($file) && is_readable($file)) {
  $data = file_get_contents($file);
  echo $data;
} else {
  echo "File not found or not readable.";
}
?>

File Upload

Forms need enctype="multipart/form-data" for files. PHP stores uploads in $_FILES. Move from tmp_name with move_uploaded_file().

Real-life example: Upload is mailing a package — PHP checks size, type, then moves it from the post office (tmp) to your shelf (uploads/).

Upload handler
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_FILES["photo"])) {
  $file = $_FILES["photo"];
  if ($file["error"] === UPLOAD_ERR_OK) {
    $dest = "uploads/" . basename($file["name"]);
    move_uploaded_file($file["tmp_name"], $dest);
    echo "Saved to $dest";
  }
}
?>
Upload form
<form method="post" enctype="multipart/form-data">
  <input type="file" name="photo" accept="image/*" />
  <button type="submit">Upload</button>
</form>

Cookies

setcookie() sends small data to the browser. $_COOKIE reads it back. Use for theme, language, or "remember me" — not passwords.

Real-life example: Cookies are sticky notes the browser keeps — "this user prefers dark mode."

Set and read cookies
<?php
setcookie("theme", "dark", [
  "expires" => time() + 86400 * 30,
  "path" => "/",
  "httponly" => true,
  "samesite" => "Lax",
]);

$theme = $_COOKIE["theme"] ?? "light";
echo "Theme: $theme";
?>

Sessions

session_start() begins server-side session storage in $_SESSION. Use for login state, shopping carts, and flash messages.

Real-life example: Sessions are a coat-check ticket — the browser holds the ticket; the server holds your coat.

Login session sketch
<?php
session_start();

if ($_SERVER["REQUEST_METHOD"] === "POST") {
  $email = $_POST["email"] ?? "";
  $_SESSION["user_email"] = $email;
  session_regenerate_id(true); // security after login
}

if (isset($_SESSION["user_email"])) {
  echo "Welcome, " . htmlspecialchars($_SESSION["user_email"]);
}
?>

PHP Filters — validate and sanitize

filter_var() validates emails, URLs, IPs, and integers. filter_input() reads superglobals safely.

Real-life example: Filters are water purifiers — dirty input goes in, cleaner data comes out.

Validate with filters
<?php
$email = "test@example.com";
$age = "25";

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  die("Bad email");
}

$age = filter_var($age, FILTER_VALIDATE_INT, [
  "options" => ["min_range" => 1, "max_range" => 120],
]);
?>

Sanitize filters

FILTER_SANITIZE_STRING (deprecated in PHP 8.1+) — use htmlspecialchars for output. FILTER_SANITIZE_EMAIL and FILTER_SANITIZE_URL clean input.

Real-life example: Sanitizing is trimming sharp edges off a toy before giving it to a child.

Sanitize examples
<?php
$dirty = "  Hello<script>alert(1)</script>  ";
$clean = htmlspecialchars(strip_tags(trim($dirty)), ENT_QUOTES, "UTF-8");
echo $clean;

$url = filter_var("https://knowvora.com/?x=1", FILTER_SANITIZE_URL);
echo $url;
?>

Advanced filters — filter_list and custom options

filter_list() shows all filter IDs. filter_has_var() checks if input exists. Combine filters with flags like FILTER_FLAG_IPV4.

Real-life example: filter_list is reading every tool name on a Swiss Army knife before picking the right blade.

Advanced filter usage
<?php
// Check if GET param exists and is valid int
if (filter_has_var(INPUT_GET, "id")) {
  $id = filter_input(INPUT_GET, "id", FILTER_VALIDATE_INT);
  if ($id !== false && $id !== null) {
    echo "Course ID: $id";
  }
}

$ip = filter_var("192.168.1.1", FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
var_dump($ip);
?>

Callbacks

A callback is a function passed to another function. array_map(), usort(), and array_filter() use callbacks often.

Real-life example: A callback is giving a friend your phone number and saying "call me when dinner is ready."

array_map and anonymous functions
<?php
$prices = [100, 200, 300];

$discounted = array_map(function ($p) {
  return $p * 0.9;
}, $prices);

print_r($discounted);

// Named callback
function double(int $n): int { return $n * 2; }
$nums = array_map("double", [1, 2, 3]);
?>

JSON — json_encode and json_decode

JSON is the standard data format for APIs. json_encode() turns PHP arrays into JSON strings. json_decode() parses JSON into arrays or objects.

Real-life example: JSON is a universal packing box — PHP, JavaScript, and mobile apps all understand the same label.

JSON encode/decode
<?php
$user = ["name" => "Asha", "courses" => ["PHP", "MySQL"]];

$json = json_encode($user);
echo $json;

$parsed = json_decode($json, true); // true = associative array
echo $parsed["name"];
?>

Exceptions

Use try { } catch (Exception $e) { } to handle errors gracefully. throw new Exception('message') signals failure.

Real-life example: Exceptions are fire alarms — normal work stops, you handle the problem, then continue safely.

try/catch/finally
<?php
function divide(int $a, int $b): float {
  if ($b === 0) {
    throw new InvalidArgumentException("Cannot divide by zero");
  }
  return $a / $b;
}

try {
  echo divide(10, 2);
  echo divide(10, 0);
} catch (InvalidArgumentException $e) {
  echo "Error: " . $e->getMessage();
} finally {
  echo "\nDone.";
}
?>

What is OOP?

Object-Oriented Programming bundles data (properties) and behavior (methods) into classes. Objects are instances of classes.

Real-life example: A class is a cookie cutter. Each cookie (object) has the same shape but different sprinkles (data).

  • Encapsulation — hide internal details
  • Inheritance — reuse parent class behavior
  • Polymorphism — same method, different classes
  • Abstraction — focus on what, not how

Classes and Objects

Define a class with class Name { }. Create objects with new Name(). Use -> to access properties and methods.

Real-life example: A Car class describes wheels and drive(). Your car object is the actual vehicle in the driveway.

Basic class
<?php
class Course {
  public string $title;
  public int $lessons;

  public function summary(): string {
    return "{$this->title} has {$this->lessons} lessons.";
  }
}

$php = new Course();
$php->title = "PHP Fundamentals";
$php->lessons = 32;
echo $php->summary();
?>

Constructor and Destructor

__construct() runs when an object is created. __destruct() runs when the object is destroyed — useful for closing files or connections.

Real-life example: Constructor is turning the key when you enter a room. Destructor is switching off lights when you leave.

Constructor / destructor
<?php
class User {
  public function __construct(
    private string $name,
    private string $email
  ) {
    echo "User created\n";
  }

  public function getName(): string {
    return $this->name;
  }

  public function __destruct() {
    echo "User destroyed\n";
  }
}

$u = new User("Asha", "asha@example.com");
echo $u->getName();
?>

Access Modifiers

public — accessible everywhere. protected — class + child classes. private — only inside the same class.

Real-life example: public is a shop window. protected is staff-only back room. private is the owner's safe.

public, protected, private
<?php
class Account {
  public string $username = "asha";
  protected float $balance = 1000.0;
  private string $pin = "1234";
}

$acc = new Account();
echo $acc->username;
// echo $acc->balance; // Error — protected
?>

Inheritance

A child class extends a parent with extends ParentClass. It inherits methods and can override them.

Real-life example: Inheritance is a family recipe — the child adds new spices but keeps the base dish.

extends and override
<?php
class Animal {
  public function speak(): string {
    return "Some sound";
  }
}

class Dog extends Animal {
  public function speak(): string {
    return "Woof!";
  }
}

$dog = new Dog();
echo $dog->speak();
?>

Class Constants

Define constants inside a class with const NAME = value. Access with ClassName::NAME or self::NAME inside the class.

Real-life example: Class constants are the company logo color — same everywhere, never changes per employee.

Class constant
<?php
class Config {
  public const SITE_NAME = "Rishtaara";
  public const MAX_UPLOAD_MB = 5;
}

echo Config::SITE_NAME;
echo Config::MAX_UPLOAD_MB . " MB max";
?>

Abstract Classes

Abstract classes cannot be instantiated directly. They may contain abstract methods that child classes must implement.

Real-life example: An abstract "Vehicle" says every vehicle must move(), but only Car and Bike fill in the details.

abstract class
<?php
abstract class Shape {
  abstract public function area(): float;

  public function describe(): string {
    return "Area: " . $this->area();
  }
}

class Circle extends Shape {
  public function __construct(private float $radius) {}

  public function area(): float {
    return pi() * $this->radius ** 2;
  }
}

$c = new Circle(5);
echo $c->describe();
?>

Interfaces

An interface lists method signatures without bodies. A class implements an interface with implements InterfaceName.

Real-life example: An interface is a job contract — "you must be able to sendEmail()" — any class hired must deliver.

interface example
<?php
interface Notifiable {
  public function notify(string $message): void;
}

class EmailNotifier implements Notifiable {
  public function notify(string $message): void {
    echo "Email sent: $message";
  }
}

$n = new EmailNotifier();
$n->notify("Welcome to Rishtaara!");
?>

Traits

Traits share methods across unrelated classes. Use trait Name inside a class body. Resolve conflicts with insteadof and as.

Real-life example: Traits are power-ups in a game — any character can equip "Loggable" without sharing a parent class.

trait example
<?php
trait Timestampable {
  public function touch(): void {
    echo "Updated at " . date("c");
  }
}

class Post {
  use Timestampable;
}

$post = new Post();
$post->touch();
?>

Static Methods and Properties

static members belong to the class, not each object. Call with ClassName::method() without creating an instance.

Real-life example: Static is the school bell — one bell for all classrooms, not a separate bell per student.

static method and property
<?php
class Counter {
  public static int $count = 0;

  public static function increment(): void {
    self::$count++;
  }
}

Counter::increment();
Counter::increment();
echo Counter::$count; // 2
?>

Namespaces

Namespaces organize code and avoid name clashes. Declare with namespace App\Models; import with use App\Models\User;

Real-life example: Namespaces are apartment numbers — User in 5A and User in 5B are different people.

namespace and use
<?php
namespace App\Services;

class Mailer {
  public function send(string $to, string $body): void {
    echo "Sent to $to";
  }
}

// another file:
// use App\Services\Mailer;
// $mail = new Mailer();
?>

Iterables

PHP 7.1+ iterable type hint accepts arrays or Traversable objects. foreach works on any iterable.

Real-life example: Iterable is anything you can walk through with foreach — a list, a queue, or a custom collection.

iterable type hint
<?php
function printLessons(iterable $lessons): void {
  foreach ($lessons as $lesson) {
    echo "- $lesson\n";
  }
}

printLessons(["Intro", "Syntax", "MySQL"]);

// Generator is iterable
function rangeGen(int $n): Generator {
  for ($i = 1; $i <= $n; $i++) yield $i;
}
printLessons(rangeGen(3));
?>

OOP recap — putting it together

Real apps combine classes, interfaces, and namespaces. Keep models (data), services (logic), and controllers (HTTP) separate.

Real-life example: OOP in a web app is a restaurant — models are ingredients, services are chefs, controllers are waiters taking orders.

Simple service class
<?php
class CourseService {
  public function __construct(private PDO $db) {}

  public function findAll(): array {
    return $this->db
      ->query("SELECT id, title FROM courses")
      ->fetchAll(PDO::FETCH_ASSOC);
  }
}
?>

When to use OOP in PHP

Use classes for anything with state and behavior — users, orders, mailers. Small scripts can stay procedural.

Real-life example: A one-line hello.php does not need OOP. A student portal with login, courses, and payments does.

  • Use type hints and return types everywhere
  • Prefer dependency injection over global state
  • Interfaces make testing and swapping implementations easy
  • Next up: MySQL — store your objects in a database

Connect to MySQL

Use PDO or MySQLi to connect PHP to MySQL. PDO is portable and supports prepared statements on multiple databases.

Real-life example: Connecting to MySQL is plugging a phone charger into the wall — PHP gets power (data) from the database.

PDO connection
<?php
try {
  $pdo = new PDO(
    "mysql:host=localhost;dbname=knowvora;charset=utf8mb4",
    "root",
    "",
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
  );
  echo "Connected!";
} catch (PDOException $e) {
  die("Connection failed: " . $e->getMessage());
}
?>

Create Database

Run CREATE DATABASE in phpMyAdmin or from PHP after connecting without a dbname. Use utf8mb4 for full Unicode support.

Real-life example: A database is a filing cabinet. CREATE DATABASE builds a new cabinet for one project.

Create database with PDO
<?php
$pdo = new PDO("mysql:host=localhost", "root", "");
$pdo->exec("CREATE DATABASE IF NOT EXISTS knowvora CHARACTER SET utf8mb4");
$pdo->exec("USE knowvora");
?>
SQL — create database
CREATE DATABASE IF NOT EXISTS knowvora
  CHARACTER SET utf8mb4
  COLLATE utf8mb4_unicode_ci;

USE knowvora;

Create Table

Tables store rows of data with columns and types. Define PRIMARY KEY, AUTO_INCREMENT, and NOT NULL where needed.

Real-life example: A table is a spreadsheet — columns are Name, Email, Score; each row is one student.

CREATE TABLE
CREATE TABLE IF NOT EXISTS students (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  email VARCHAR(150) NOT NULL UNIQUE,
  score INT DEFAULT 0,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Create table from PHP
<?php
$sql = "CREATE TABLE IF NOT EXISTS courses (
  id INT AUTO_INCREMENT PRIMARY KEY,
  title VARCHAR(200) NOT NULL,
  level ENUM('beginner','intermediate','advanced') DEFAULT 'beginner'
)";
$pdo->exec($sql);
?>

Insert Data

INSERT INTO adds new rows. Match column names to values. Never put raw user input directly into SQL strings.

Real-life example: INSERT is adding a new contact to your phone — name, number, email in the right fields.

INSERT statement
INSERT INTO students (name, email, score)
VALUES ('Asha Khan', 'asha@example.com', 88);
Insert from PHP
<?php
$stmt = $pdo->prepare(
  "INSERT INTO students (name, email, score) VALUES (:name, :email, :score)"
);
$stmt->execute([
  ":name" => "Ravi Patel",
  ":email" => "ravi@example.com",
  ":score" => 92,
]);
?>

Get Last Insert ID

After INSERT, lastInsertId() returns the AUTO_INCREMENT id of the new row — useful for linking related records.

Real-life example: Last ID is the ticket number printed after you join a queue — you need it for the next step.

lastInsertId()
<?php
$stmt = $pdo->prepare("INSERT INTO students (name, email) VALUES (?, ?)");
$stmt->execute(["Asha", "asha@example.com"]);

$newId = $pdo->lastInsertId();
echo "New student ID: $newId";
?>

Insert Multiple & Prepared Statements

Insert many rows with multiple VALUES or a loop. Prepared statements bind placeholders (? or :name) to prevent SQL injection.

Real-life example: Prepared statements are sealed envelopes — the post office knows the slot size; attackers cannot slip in extra instructions.

Multiple insert
INSERT INTO students (name, email, score) VALUES
  ('Asha', 'a@ex.com', 88),
  ('Ravi', 'r@ex.com', 92),
  ('Meera', 'm@ex.com', 85);
Prepared statement with placeholders
<?php
$stmt = $pdo->prepare("INSERT INTO courses (title, level) VALUES (:title, :level)");

foreach ([["PHP", "beginner"], ["MySQL", "intermediate"]] as [$t, $l]) {
  $stmt->execute([":title" => $t, ":level" => $l]);
}
?>

Select Data

SELECT chooses columns FROM a table. fetch() gets one row; fetchAll() gets every row as an array.

Real-life example: SELECT is searching a library catalog — you pick which book details to see.

SELECT and fetchAll
<?php
$stmt = $pdo->query("SELECT id, name, score FROM students");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($rows as $row) {
  echo $row["name"] . ": " . $row["score"] . "\n";
}
?>
SQL SELECT
SELECT id, name, email, score FROM students;
SELECT name FROM students WHERE score >= 80;

Where Clause

WHERE filters rows. Use AND, OR, IN, LIKE, and BETWEEN. Always bind user values in prepared statements.

Real-life example: WHERE is a filter on a shopping site — show only shoes, size 9, under ₹2000.

WHERE with prepared params
<?php
$minScore = 80;
$stmt = $pdo->prepare("SELECT * FROM students WHERE score >= :min ORDER BY score DESC");
$stmt->execute([":min" => $minScore]);
$top = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
SQL WHERE examples
SELECT * FROM students WHERE name LIKE 'A%';
SELECT * FROM students WHERE score BETWEEN 70 AND 90;
SELECT * FROM students WHERE id IN (1, 3, 5);

Order By

ORDER BY sorts results ASC (default) or DESC. Sort by one or more columns.

Real-life example: ORDER BY is sorting a playlist — by artist name A–Z or by date newest first.

ORDER BY
SELECT name, score FROM students
ORDER BY score DESC, name ASC;

Delete Data

DELETE FROM removes rows. Always use WHERE — DELETE without WHERE wipes the entire table.

Real-life example: DELETE is removing expired items from a fridge — specify which items, not everything.

Safe DELETE
<?php
$id = filter_input(INPUT_POST, "id", FILTER_VALIDATE_INT);
if ($id) {
  $stmt = $pdo->prepare("DELETE FROM students WHERE id = :id");
  $stmt->execute([":id" => $id]);
  echo "Deleted row $id";
}
?>
SQL DELETE
DELETE FROM students WHERE id = 5;
DELETE FROM students WHERE score < 50;

Update Data

UPDATE table SET column = value WHERE condition changes existing rows. Combine with prepared statements.

Real-life example: UPDATE is editing one row in a spreadsheet — change Asha's score from 88 to 90.

UPDATE with PDO
<?php
$stmt = $pdo->prepare(
  "UPDATE students SET score = :score WHERE id = :id"
);
$stmt->execute([":score" => 95, ":id" => 1]);
echo "Rows updated: " . $stmt->rowCount();
?>
SQL UPDATE
UPDATE students SET score = 90 WHERE name = 'Asha';
UPDATE courses SET level = 'advanced' WHERE id = 3;

Limit

LIMIT caps how many rows return — essential for pagination. Use OFFSET for page 2, 3, etc.

Real-life example: LIMIT is reading only the first 10 search results instead of all million matches.

LIMIT and pagination
<?php
$page = 2;
$perPage = 10;
$offset = ($page - 1) * $perPage;

$stmt = $pdo->prepare(
  "SELECT * FROM students ORDER BY id LIMIT :limit OFFSET :offset"
);
$stmt->bindValue(":limit", $perPage, PDO::PARAM_INT);
$stmt->bindValue(":offset", $offset, PDO::PARAM_INT);
$stmt->execute();
?>
SQL LIMIT
SELECT * FROM students ORDER BY score DESC LIMIT 5;
SELECT * FROM students LIMIT 10 OFFSET 20; -- page 3, 10 per page

XML Parsers overview

XML stores structured data in tags. PHP can read XML with SimpleXML (easy), XML Parser (Expat, event-based), or DOMDocument (full tree).

Real-life example: XML is a labeled packing list — each <item> tag describes one product in the shipment.

Sample XML
<?xml version="1.0" encoding="UTF-8"?>
<courses>
  <course id="1">
    <title>PHP Fundamentals</title>
    <lessons>32</lessons>
  </course>
  <course id="2">
    <title>MySQL Basics</title>
    <lessons>20</lessons>
  </course>
</courses>

SimpleXML

simplexml_load_file() or simplexml_load_string() turns XML into an object you can traverse with -> and foreach.

Real-life example: SimpleXML is reading a short menu — quick glance, pick items by name.

SimpleXML read
<?php
$xml = simplexml_load_string('<?xml version="1.0"?><root><name>Rishtaara</name></root>');
echo $xml->name;

$books = simplexml_load_file("courses.xml");
foreach ($books->course as $course) {
  echo (string) $course->title . "\n";
}
?>

XML Parser (Expat) and DOM

xml_parser_create() (Expat) fires callbacks on start/end tags — memory efficient for huge files. DOMDocument builds a full editable tree.

Real-life example: Expat is a conveyor belt — items pass one at a time. DOM is spreading the whole puzzle on a table to move pieces.

DOMDocument
<?php
$dom = new DOMDocument();
$dom->load("courses.xml");
$titles = $dom->getElementsByTagName("title");

foreach ($titles as $node) {
  echo $node->textContent . "\n";
}
?>
Expat-style parser (concept)
<?php
$parser = xml_parser_create();
xml_parse_into_struct($parser, file_get_contents("courses.xml"), $values);
xml_parser_free($parser);
print_r($values);
?>

AJAX Introduction

AJAX (Asynchronous JavaScript and XML) loads data in the background without reloading the page. Today we mostly use JSON instead of XML.

Real-life example: AJAX is texting the kitchen for today's specials while you keep chatting at the table — no need to stand up and walk over.

  • Browser sends HTTP request via fetch() or XMLHttpRequest
  • PHP script returns JSON or HTML fragment
  • JavaScript updates part of the page
  • User sees fast, app-like experience

PHP as AJAX endpoint

A PHP API file sets Content-Type: application/json, reads input, queries data, and echo json_encode($result).

Real-life example: PHP endpoint is a vending machine slot — JavaScript inserts coins (request), PHP drops the snack (JSON).

api/courses.php
<?php
header("Content-Type: application/json");

$courses = [
  ["id" => 1, "title" => "PHP Fundamentals"],
  ["id" => 2, "title" => "MySQL Basics"],
];

echo json_encode($courses);
fetch from JavaScript
fetch("/api/courses.php")
  .then((res) => res.json())
  .then((data) => {
    console.log(data);
    document.getElementById("list").innerHTML =
      data.map((c) => `<li>${c.title}</li>`).join("");
  });

AJAX with Database

PHP reads POST/GET params, runs a prepared SELECT, and returns JSON rows. JavaScript renders a table or list.

Real-life example: AJAX + database is a live scoreboard — refresh numbers without reloading the whole stadium screen.

search.php — JSON from MySQL
<?php
header("Content-Type: application/json");
require "db.php";

$q = trim($_GET["q"] ?? "");
$stmt = $pdo->prepare(
  "SELECT id, name, score FROM students WHERE name LIKE :q LIMIT 10"
);
$stmt->execute([":q" => "%$q%"]);
echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
Client fetch
async function search(name) {
  const res = await fetch(`/search.php?q=${encodeURIComponent(name)}`);
  const rows = await res.json();
  return rows;
}

AJAX with XML

Some legacy APIs return XML. PHP can echo XML headers and build strings, or JavaScript parses response as text then DOMParser.

Real-life example: XML AJAX is receiving a fax — older format, but still readable with the right machine.

PHP XML response
<?php
header("Content-Type: application/xml");
echo '<?xml version="1.0"?>';
echo "<results><item>PHP</item><item>MySQL</item></results>";
Parse XML in JavaScript
fetch("/api/tags.xml")
  .then((r) => r.text())
  .then((xmlText) => {
    const doc = new DOMParser().parseFromString(xmlText, "text/xml");
    const items = doc.querySelectorAll("item");
    items.forEach((el) => console.log(el.textContent));
  });

AJAX Live Search

Live search sends a request on every keystroke (with debounce). PHP filters database rows and returns JSON matches.

Real-life example: Live search is Google suggestions — type one letter and the list updates instantly.

Live search HTML + JS
<input type="text" id="search" placeholder="Search courses..." />
<ul id="results"></ul>
<script>
  let timer;
  document.getElementById("search").addEventListener("input", (e) => {
    clearTimeout(timer);
    timer = setTimeout(async () => {
      const q = e.target.value;
      if (q.length < 2) return;
      const res = await fetch(`/live-search.php?q=${encodeURIComponent(q)}`);
      const data = await res.json();
      document.getElementById("results").innerHTML =
        data.map((r) => `<li>${r.title}</li>`).join("");
    }, 300);
  });
</script>
live-search.php
<?php
header("Content-Type: application/json");
require "db.php";
$q = "%" . trim($_GET["q"] ?? "") . "%";
$stmt = $pdo->prepare("SELECT title FROM courses WHERE title LIKE :q LIMIT 8");
$stmt->execute([":q" => $q]);
echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));

AJAX Poll

A poll lets users vote without page reload. JavaScript POSTs the choice; PHP saves to MySQL and returns updated counts as JSON.

Real-life example: An AJAX poll is raising hands in a webinar chat — votes tally live without stopping the speaker.

vote.php
<?php
header("Content-Type: application/json");
require "db.php";

if ($_SERVER["REQUEST_METHOD"] === "POST") {
  $option = (int) ($_POST["option"] ?? 0);
  $stmt = $pdo->prepare("UPDATE poll SET votes = votes + 1 WHERE id = :id");
  $stmt->execute([":id" => $option]);
}

$counts = $pdo->query("SELECT id, label, votes FROM poll")->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($counts);
Vote with fetch
async function vote(optionId) {
  const body = new FormData();
  body.append("option", optionId);
  const res = await fetch("/vote.php", { method: "POST", body });
  const results = await res.json();
  renderChart(results);
}

Examples & Reference overview

You now cover the full Rishtaara PHP syllabus — basics through AJAX. Build small projects: contact form, login, CRUD app, live search.

Real-life example: Finishing this course is earning a driver's license — next you practice on real roads (Laravel, WordPress, APIs).

  • PHP manual: php.net — search any function
  • MySQL docs for advanced queries and indexes
  • Practice CRUD on a student or product table
  • Combine sessions + PDO + AJAX for a mini dashboard

Certificate, practice & what's next

Test your knowledge with MCQs and interview questions. Then explore Laravel for larger apps or WordPress for CMS work.

Real-life example: MCQs are a mock exam before the real job interview — find gaps while it is still safe.

  • MCQ practice: /mcq/php-mcq
  • Interview prep: /interview/php-interview
  • Knowledge guide: /knowledge/php-fundamentals
  • Next course: Laravel or full-stack projects on Rishtaara
Congratulations — you completed all 32 PHP lessons. Keep building projects; that is where syntax becomes skill.

Key Takeaways

  • PHP runs on the server — it builds HTML, handles forms, and talks to MySQL.
  • Always validate input on the server and escape output with htmlspecialchars().
  • Use PDO prepared statements — never concatenate user input into SQL.
  • Superglobals ($_GET, $_POST, $_SESSION) carry request and session data.
  • OOP organizes backend code — classes, interfaces, traits, and namespaces.
  • Sessions and cookies manage login state; regenerate session ID after login.
  • JSON is the standard format for APIs and AJAX responses.
  • MySQL CRUD (Create, Read, Update, Delete) powers most PHP apps.
  • AJAX loads data without page reload — combine fetch + PHP + JSON.
  • Practice with MCQs and small projects to turn syntax into real skill.

Frequently Asked Questions

Should beginners learn plain PHP before Laravel?
Yes. Syntax, forms, PDO, sessions, and OOP basics make Laravel much easier to understand and debug.
Is PDO better than mysqli for most projects?
PDO is generally preferred for portability and clean prepared statements. mysqli is fine but more MySQL-specific.
How do I secure PHP login systems?
Use password_hash/password_verify, session_regenerate_id after login, CSRF tokens, htmlspecialchars on output, and HTTPS with secure cookies.
When should I use AJAX in PHP apps?
Use AJAX when you need partial page updates — live search, polls, infinite scroll, or dashboards — without full reloads.
echo vs print — which should I use?
Prefer echo — it is faster, accepts multiple arguments, and is used in most PHP codebases and frameworks.