PHP and MySQL Notes
DSC course under University of Kerala (UoK FYUGP Regulations). Credits: 4 | 60 Hours (4 Hrs/Week).
Chapter-Wise Module Notes & PDF Downloads
Short Notes
All Modules IncludedComplete syllabus revision notes covering all modules in one single PDF
Module 1
Introduction to PHP
Module 2
Arrays and OOP
Module 3
Forms, State Management, and Images
Module 4
MySQL and PHP-MySQL Integration
Module 5
Dynamic Websites, Superglobals, and Lab Integration
Read Module Notes Online
Module I: Introduction to PHP
Chapter 1: Overview of PHP and Server-Side Architecture
1.1 Evolution and Role of PHP in Web Engineering
PHP, originally created as Personal Home Page Tools and now maintained as the recursive acronym PHP: Hypertext Preprocessor, is a widely deployed open-source, general-purpose server-side scripting language engineered specifically for dynamic web development. Unlike client-side languages such as JavaScript that execute inside the user's web browser, PHP executes on the web server before any Hypertext Markup Language (HTML) payload is transmitted over Hypertext Transfer Protocol (HTTP) to the client.
When a client browser requests a resource with a .php extension, the web server (such as Apache HTTP Server or Nginx) delegates the file to the PHP interpreter, powered by the Zend Engine. The interpreter parses the script, executes embedded PHP logic, interacts with relational databases or external services if instructed, and emits pure HTML, Cascading Style Sheets (CSS), JavaScript, or JavaScript Object Notation (JSON) back to the web server. The web server then wraps the generated output in an HTTP response and delivers it to the client. Consequently, the end user never sees the underlying PHP source code, database credentials, or proprietary business logic.
Over successive major releases (from PHP 5 through PHP 7 and PHP 8), the language evolved from simple procedural template scripting into a high-performance runtime supporting Just-In-Time (JIT) compilation, strict scalar type declarations, modern object-oriented programming, exception hierarchies, and standardized package ecosystems via Composer.
1.2 Request-Response Lifecycle in a PHP Environment
Understanding how a PHP application processes an incoming request is foundational for debugging, state management, and performance tuning. The execution lifecycle proceeds through five deterministic stages:
- Stage 1 — Client Request Dispatch: The browser issues an HTTP GET or POST request targeting a Uniform Resource Locator (URL) such as
http://localhost/portal/profile.php?id=42, carrying request headers, cookies, and optional form body payloads. - Stage 2 — Web Server Routing: Apache or Nginx inspects the file extension and routes the request to the PHP runtime via
mod_phpor PHP-FPM (FastCGI Process Manager). Static assets such as images and stylesheets are served directly by the web server without invoking PHP. - Stage 3 — Lexical Analysis and Opcode Compilation: The Zend Engine tokenizes the script, builds an Abstract Syntax Tree (AST), and compiles it into intermediate Zend opcodes. When OPcache is enabled, compiled opcodes remain in shared memory across requests, eliminating repeated parsing overhead.
- Stage 4 — Runtime Execution and I/O: The engine executes opcodes sequentially, populating superglobal arrays, evaluating control structures, invoking functions, and querying MySQL or reading local files.
- Stage 5 — Response Transmission and Teardown: Standard output buffered during execution is flushed to the web server with HTTP status codes and headers, and all per-request memory allocations, open handles, and variables are automatically reclaimed when the script terminates.
1.3 Benefits and Drawbacks of PHP as a Server-Side Script
Choosing PHP as a server-side technology involves weighing its operational strengths against architectural trade-offs inherent to shared-nothing, request-scoped scripting.
| Dimension | Benefits of Server-Side PHP | Drawbacks and Limitations |
|---|---|---|
| Platform & Cost | Open-source under the PHP License; runs natively on Linux, Windows, and macOS with Apache, Nginx, and IIS at zero licensing cost. | Shared-hosting environments often run outdated PHP versions with restricted php.ini configuration privileges. |
| Database Integration | Native, high-performance extensions for MySQL (MySQLi, PDO), PostgreSQL, SQLite, and Redis are built into standard distributions. | Legacy codebases frequently mix raw SQL strings with HTML presentation, increasing maintenance overhead if not structured properly. |
| Security Model | Business logic, database credentials, and validation rules execute strictly on the server and remain hidden from browser inspection tools. | Weakly disciplined developers may introduce SQL injection, Cross-Site Scripting (XSS), or insecure file upload vulnerabilities. |
| Execution Model | Shared-nothing architecture isolates each HTTP request, preventing memory leaks from crashing subsequent requests. | Re-bootstrapping application state on every HTTP request adds overhead compared to long-running daemon processes unless OPcache is tuned. |
| Learning Curve & Ecosystem | C-like syntax allows rapid onboarding; Composer provides modern dependency management and PSR interoperability standards. | Historical inconsistencies in built-in function naming and parameter order (needle vs. haystack) require careful reference checking. |
| Concurrency & Async I/O | Web servers handle thousands of parallel requests through worker pools with predictable per-request memory isolation. | Standard PHP lacks native persistent WebSocket or background event-loop concurrency without external extensions like Swoole. |
1.4 Embedding PHP in HTML and Development Stack Setup
PHP code blocks are delimited by canonical opening and closing tags: <?php and ?>. When a file contains pure PHP code, omitting the closing ?> tag is recommended by modern coding standards to prevent accidental trailing whitespace from corrupting HTTP headers or triggering premature output errors. Short echo tags <?= $expr ?> provide a concise shorthand for outputting escaped values inside HTML templates. Local development typically relies on bundled stacks such as XAMPP (Cross-Platform, Apache, MariaDB/MySQL, PHP, Perl) or WAMP (Windows, Apache, MySQL, PHP), where project files reside inside the htdocs or www document root and configuration directives live in php.ini.
<?php
$courseTitle = "PHP and MySQL";
$semester = 5;
$creditHours = 4;
$institution = "University of Kerala";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?php echo htmlspecialchars($courseTitle); ?></title>
</head>
<body>
<h1>Course: <?= htmlspecialchars($courseTitle) ?></h1>
<p>Institution: <?= htmlspecialchars($institution) ?></p>
<p>Semester: <?php print $semester; ?> | Credits: <?php echo $creditHours; ?></p>
<p>Server Timestamp: <?php echo date("Y-m-d H:i:s"); ?></p>
</body>
</html>Chapter 2: PHP Language Basics, Variables, and Superglobals
2.1 Lexical Rules, Comments, and Output Statements
Every PHP statement terminates with a semicolon (;). PHP keywords (such as if, echo, function, and return) and function names are case-insensitive, whereas variable names and constants are strictly case-sensitive. Three comment styles are supported: single-line C++ style (// comment), single-line shell style (# comment), and multi-line C style (/* comment */). Multi-line comments cannot be nested, so developers use single-line comments inside blocks when temporarily disabling code.
Two primary language constructs emit output: echo and print. Although both output strings, echo accepts multiple comma-separated expressions and has no return value, whereas print accepts a single argument and always returns integer 1, allowing it to participate in expressions. For diagnostic inspection during development, var_dump() prints type, length, and value, while print_r() prints human-readable representations of arrays and objects.
2.2 Variables, Naming Rules, and Constants
A PHP variable is prefixed with a dollar sign ($) followed by an underscore or ASCII letter, and then any combination of letters, digits, or underscores. Variable names cannot begin with a digit or contain spaces. PHP is dynamically typed: a variable does not require explicit type declaration before assignment, and its underlying type can change during execution when reassigned a value of a different type. Variable variables ($name) allow dynamic resolution where the value of one variable serves as the identifier of another, though they are used sparingly to preserve code clarity.
Constants represent immutable identifiers bound via define('SITE_NAME', 'DegreeLive') or the compile-time const MAX_ATTEMPTS = 5; keyword. Unlike variables, constants do not carry a $ prefix, cannot be redefined or unset once declared, and possess global visibility across all scopes.
2.3 Global Scope and the $GLOBALS Array
Variables declared outside any function reside in the global scope. Unlike C or JavaScript, PHP functions do not automatically inherit access to global variables. This design prevents accidental mutation of application-wide state by helper routines. To read or mutate a global variable from inside a function body, the developer must either import it explicitly using the global keyword or index into the associative $GLOBALS superglobal array, whose keys correspond directly to global variable names.
2.4 Superglobal Arrays in PHP
Superglobals are built-in associative arrays that are automatically populated by the PHP runtime and remain accessible across every scope without requiring a global declaration. They form the primary interface between the web server, the HTTP request, and the PHP script.
| Superglobal | Purpose and Data Source | Common Practical Usage |
|---|---|---|
$GLOBALS |
References all variables currently defined in the global scope of the script. | Accessing or modifying global configuration flags inside deeply nested helper functions. |
$_SERVER |
Contains web server headers, file paths, script locations, and execution environment metadata. | Checking $_SERVER['REQUEST_METHOD'], $_SERVER['REMOTE_ADDR'], or $_SERVER['PHP_SELF']. |
$_GET |
Associative array of key-value pairs parsed from the URL query string after ?. |
Reading search filters, pagination numbers, and record identifiers. |
$_POST |
Associative array of variables submitted via HTTP POST request body (urlencoded or multipart). | Processing login credentials, registration forms, and database write operations. |
$_REQUEST |
Merged collection containing contents of $_GET, $_POST, and $_COOKIE (configured via request_order). |
Quick prototyping where input source is flexible; avoided in strict security contexts. |
$_FILES |
Two-dimensional array holding metadata for files uploaded via multipart/form-data POST requests. |
Inspecting name, type, tmp_name, error, and size before moving uploads. |
$_COOKIE |
Associative array of HTTP cookies sent by the client browser in the Cookie request header. |
Reading user preferences, theme settings, or persistent remember-me tokens. |
$_SESSION |
Associative array storing server-side session variables persisted across requests for an active user. | Maintaining authenticated user IDs, shopping carts, and multi-step form wizards. |
$_ENV |
Variables imported from the operating system environment under which PHP is executing. | Retrieving database passwords or API keys injected via container or server configuration. |
<?php
$appVersion = "2.4.1";
$environment = "Production";
define("DEFAULT_TIMEZONE", "Asia/Kolkata");
function printSystemBanner() {
global $appVersion;
$method = $_SERVER['REQUEST_METHOD'] ?? 'CLI';
$script = $_SERVER['SCRIPT_NAME'] ?? 'index.php';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
echo "Version: " . $appVersion . " | Env: " . $GLOBALS['environment'] . "\n";
echo "Method: " . $method . " | Host: " . $host . " | Script: " . $script . "\n";
echo "Timezone: " . DEFAULT_TIMEZONE . "\n";
}
printSystemBanner();
?>Chapter 3: Data Types, Type Manipulation, and Operators
3.1 Scalar, Compound, and Special Data Types
PHP categorizes values into ten primitive types grouped across three families: scalar types, compound types, and special types.
- Scalar Types:
int(signed integers such as42,-10, hexadecimal0x1A, or binary0b1010),float(IEEE 754 double-precision floating-point numbers such as3.14159or scientific notation1.2e3),string(byte sequences enclosed in single quotes for literal strings or double quotes for variable interpolation and escape sequences like\n), andbool(trueorfalse). - Compound Types:
array(ordered hash map supporting indexed, associative, and nested structures),object(instance of a class encapsulating state and behavior),callable(callback reference to a function or method), anditerable(pseudo-type accepting arrays orTraversableobjects). - Special Types:
NULL(represents a variable with no assigned value, unassigned variables, or variables explicitly cleared viaunset()) andresource(special handle referencing external resources such as open file streams, GD image canvases, or database links).
3.2 String Delimiters: Single Quotes, Double Quotes, Heredoc, and Nowdoc
String literals can be written in four distinct syntactic forms. Single-quoted strings ('Hello $name') treat characters literally without interpolating variables, parsing only \' and \\. Double-quoted strings ("Hello {$name}") interpolate variables and interpret escape sequences such as \n, \r, and \t. Heredoc syntax (<<<EOD ... EOD;) spans multiple lines with variable interpolation like double quotes, whereas Nowdoc syntax (<<<'EOD' ... EOD;) spans multiple lines without interpolation, ideal for embedding raw SQL or HTML snippets.
3.3 Testing Types, Typecasting, and settype()
Because PHP performs automatic type juggling during loose comparisons and arithmetic operations, developers frequently verify or coerce types explicitly to prevent subtle logic defects.
- Testing Types: The
gettype($var)function returns a human-readable string identifying the variable's current type, whilevar_dump($var)prints both type and value. Strict predicate functions return booleans:is_int(),is_float(),is_string(),is_bool(),is_array(),is_object(),is_null(), andis_numeric(). Furthermore,isset($var)checks whether a variable is declared and notNULL, whereasempty($var)evaluates whether a variable is missing,0,"",false, or[]. - Typecasting: Explicit casting creates a temporary converted value without mutating the original variable's type. Syntax uses C-style parenthesized casts:
(int),(float),(string),(bool),(array), and(object). For example,$age = (int) "21 years";evaluates to integer21, while(bool) ""evaluates tofalse. - In-Place Conversion via settype(): Unlike typecasting,
settype($var, "integer")permanently mutates the variable itself to the target type and returnstrueon success orfalseon failure. Supported type strings include"boolean","integer","float","string","array","object", and"null".
<?php
$rawInput = "125.75";
echo "Initial type: " . gettype($rawInput) . "\n"; // string
// Typecasting preserves original variable type
$asFloat = (float) $rawInput;
echo "Cast float: " . $asFloat . " | Original still: " . gettype($rawInput) . "\n";
// settype() mutates the variable directly
$success = settype($rawInput, "integer");
if ($success) {
echo "After settype: " . $rawInput . " (" . gettype($rawInput) . ")\n"; // 125 (integer)
}
var_dump(is_int($rawInput), is_string($rawInput), isset($rawInput), empty($rawInput));
?>3.4 Operators, Expressions, and Precedence
PHP provides a rich set of operators governed by strict precedence and associativity rules. Arithmetic operators (+, -, *, /, %, ** for exponentiation) operate on numeric operands. Note that dividing two integers that do not divide evenly automatically yields a float; use intdiv($a, $b) for integer division. The string concatenation operator is the period (.), and its compound assignment counterpart is .=. Assignment operators include =, +=, -=, *=, /=, and ??= (null coalescing assignment).
Comparison operators distinguish between loose equality (==, which performs type juggling) and strict identity (===, which requires both equal value and identical data type). Similarly, != and <> test loose inequality, while !== tests strict non-identity. The spaceship operator (<=>) performs three-way comparison, returning -1, 0, or 1. Logical operators include && / and, || / or, xor, and !, where && and || have higher precedence than their English-word equivalents and support short-circuit evaluation.
Consider a billing expression evaluating operator precedence in PHP, computing a discounted total price with tax:
Worked Numerical Example: Suppose P = 1,000, d = 0.10, and r = 0.18. First, the discount amount is 1,000 × 0.10 = 100, leaving a discounted subtotal of 1,000 − 100 = 900. Multiplying by (1 + 0.18) = 1.18 yields T = 900 × 1.18 = 1,062.00.
| Operator Group | Operators | Associativity | Key Semantics |
|---|---|---|---|
| Unary & Increment | ++, --, !, (int) |
Right | Pre-increment mutates before returning; post-increment returns before mutating. |
| Arithmetic | **, *, /, %, +, - |
Left (** Right) |
** binds tighter than unary minus; % computes integer remainder. |
| Comparison | <, >, ==, ===, <=> |
Non-associative | Prefer === and !== to avoid unexpected string-to-number coercion. |
| Logical | &&, ||, and, or, xor |
Left | Short-circuits right operand as soon as truth value is determined. |
| Null Coalescing | ?? |
Right | Returns left operand if it exists and is not NULL; otherwise evaluates right. |
Chapter 4: Flow Control Statements and Functions
4.1 Conditional Branching and Iteration Constructs
Flow control constructs direct execution along conditional branches or iterative loops:
- Conditional Branching:
if,elseif, andelseevaluate boolean conditions sequentially. Theswitchstatement compares a single expression against multiplecaselabels using loose equality and requiresbreakto prevent fall-through. Modern PHP also supports the strict-comparisonmatchexpression, which returns a value directly without fall-through. - Ternary and Null Coalescing: The ternary operator
$cond ? $a : $bprovides compact conditional expressions, while the null coalescing operator$val = $_GET['page'] ?? 1;safely returns a fallback when the left operand is missing orNULLwithout triggering a missing-key warning. - Iteration Constructs:
whiletests its condition before each iteration (entry-controlled);do...whileexecutes the body at least once before testing (exit-controlled);forgroups initialization, condition, and increment expressions; andforeachiterates cleanly over arrays and iterable objects, exposing either values or key-value pairs. - Loop Jump Controls:
breakexits the enclosing loop or switch immediately (accepting an optional numeric depth likebreak 2;), whilecontinueskips the remainder of the current iteration and advances to the next cycle.
<?php
$marks = [88, 74, 92, 61, 45];
$total = 0;
foreach ($marks as $index => $score) {
if ($score < 50) {
$grade = "Needs Improvement";
} elseif ($score >= 85) {
$grade = "Distinction";
} else {
$grade = "Pass";
}
echo "Subject " . ($index + 1) . ": $score ($grade)\n";
$total += $score;
}
$average = $total / count($marks);
echo "Overall Average: " . number_format($average, 2) . "\n";
?>4.2 Defining and Calling User-Defined Functions
Functions encapsulate reusable logic into named, modular units. A function is declared using the function keyword followed by a valid identifier, a parenthesized parameter list, and a curly-braced body. Functions may be invoked either before or after their definition in the same file (except when conditionally defined), because PHP parses top-level function declarations during compilation. Modern PHP also supports type hints on parameters and return types (such as function add(int $a, int $b): int).
4.3 Variable Scope: Local, Global, and Static
Scope governs where a variable can be read or modified during script execution:
- Local Scope: Variables declared inside a function exist only during that function's invocation and are destroyed upon return.
- Global Scope: Variables declared outside functions are accessible inside a function only via
global $var;or$GLOBALS['var']. - Static Variables: Prefixing a local variable with
staticpreserves its value across multiple calls to the same function while keeping its visibility strictly local. This is ideal for call counters, memoization caches, or singleton-like helpers.
4.4 Returning Values, Default Arguments, and Pass-by-Reference
A function returns a value to its caller using the return statement, which immediately terminates execution of the function. To return multiple values, a function returns an array that the caller can destructure using [$min, $max] = getBounds($data);. Optional parameters may specify default scalar or constant values (such as function greet($name, $role = "Student")), which must appear to the right of all required parameters.
By default, PHP passes arguments by value, meaning modifications made to a parameter inside the function do not affect the caller's original variable. Prefixing a parameter with an ampersand (&$value) enables pass-by-reference, binding the parameter directly to the caller's variable memory slot so changes inside the function mutate the original variable.
<?php
function trackVisits() {
static $counter = 0;
$counter++;
return $counter;
}
function applyBonus(&$salary, $bonusPercent = 10) {
$salary += $salary * ($bonusPercent / 100);
}
function getMinMax(array $nums) {
return [min($nums), max($nums)];
}
echo "Call 1: " . trackVisits() . "\n"; // 1
echo "Call 2: " . trackVisits() . "\n"; // 2
$empSalary = 40000;
applyBonus($empSalary); // Uses default 10%
echo "Updated Salary: " . $empSalary . "\n"; // 44000
[$low, $high] = getMinMax([12, 45, 7, 89, 23]);
echo "Min: $low, Max: $high\n";
?>4.5 Essential Built-In Functions
PHP ships with thousands of compiled C-level built-in functions organized into core modules. Mathematical helpers include abs(), round(), ceil(), floor(), pow(), sqrt(), min(), max(), and random_int(). Variable inspection and serialization helpers include isset(), empty(), unset(), var_dump(), print_r(), json_encode(), and json_decode(). Leveraging built-in functions reduces code volume and executes substantially faster than equivalent user-space loops.
Chapter 5: Advanced Function Patterns, Error Handling, and Worked Execution Traces
5.1 Anonymous Functions, Closures, Arrow Functions, and Variadics
Beyond named functions, modern PHP supports first-class functions that can be assigned to variables, passed as callbacks to array utilities, or returned from factory functions:
- Anonymous Functions (Closures): Declared without a name and assigned to a variable, such as
$square = function ($x) { return $x * $x; };. To capture variables from the enclosing scope, closures explicitly declare ause ($taxRate)clause. - Arrow Functions: Introduced in PHP 7.4 using
fn($x) => $x * $factor, arrow functions automatically capture outer-scope variables by value and implicitly return a single expression. - Variadic Functions: Prefixing the final parameter with the splat operator (
...$numbers) allows a function to accept an arbitrary number of arguments, automatically packed into an array inside the function body.
5.2 Recursion and Stack Frame Execution
A recursive function invokes itself to solve a problem by decomposing it into smaller subproblems until reaching a terminating base case. Without a valid base case, recursion exhausts the call stack or triggers PHP's maximum nesting limit. Consider computing the factorial of a non-negative integer:
Worked Trace for n = 4: Calling factorial(4) pushes stack frames for 4 * factorial(3), 3 * factorial(2), and 2 * factorial(1). When factorial(1) returns 1, the frames unwind sequentially: 2 * 1 = 2, 3 * 2 = 6, and finally 4 * 6 = 24.
5.3 PHP Error Levels, Configuration, and Exception Handling
Robust server-side scripts distinguish between non-fatal notices/warnings, fatal runtime errors, and catchable exceptions. During development, error_reporting(E_ALL); ini_set('display_errors', '1'); surfaces every diagnostic message immediately. In production, display_errors must be set to 0 while log_errors = 1 writes diagnostics privately to the server log file so internal file paths and SQL fragments are never exposed to end users.
| Error Constant | Severity | Common Trigger Scenario |
|---|---|---|
E_ERROR |
Fatal run-time error | Calling a non-existent function or exhausting memory limit; halts execution immediately. |
E_WARNING |
Non-fatal run-time warning | Missing file passed to include or division by zero in older code; script continues. |
E_PARSE |
Compile-time syntax error | Missing semicolon or unclosed brace; script fails before execution begins. |
E_NOTICE / E_WARNING |
Advisory diagnostic | Reading an uninitialized variable or accessing a missing array key. |
Exception / Error |
Throwable object | Explicitly thrown via throw new InvalidArgumentException(...) and handled in try-catch-finally. |
<?php
declare(strict_types=1);
function sumAll(int ...$nums): int {
return array_sum($nums);
}
function factorial(int $n): int {
if ($n < 0) {
throw new InvalidArgumentException("Negative input not permitted.");
}
if ($n <= 1) {
return 1;
}
return $n * factorial($n - 1);
}
$taxRate = 0.18;
$addTax = fn(float $price): float => $price * (1 + $taxRate);
echo "Sum: " . sumAll(10, 20, 30, 40) . "\n";
echo "With Tax: " . number_format($addTax(500.0), 2) . "\n";
try {
echo "4! = " . factorial(4) . "\n";
echo factorial(-2);
} catch (InvalidArgumentException $e) {
echo "Caught error: " . $e->getMessage() . "\n";
} finally {
echo "Execution block completed.\n";
}
?>Module II: Arrays and OOP
Chapter 1: PHP Arrays and Array Manipulation Functions
1.1 Indexed, Associative, and Multidimensional Arrays
In PHP, an array is not a fixed-size contiguous C block; rather, it is an ordered hash map that associates keys (integers or strings) with values of any type. This unified data structure seamlessly supports lists, dictionaries, stacks, queues, and nested trees. Every element maintains insertion order unless explicitly sorted or re-indexed.
- Indexed Arrays: Keys are sequential integers starting at
0by default. Created using short bracket syntax$langs = ["PHP", "SQL", "HTML"];or legacyarray(...). Appending an element without specifying an index via$langs[] = "CSS";assigns the next highest integer key automatically. - Associative Arrays: Keys are descriptive strings mapped to values via the
=>operator, such as$student = ["id" => 101, "name" => "Ananya", "gpa" => 8.9];. Associative arrays form the backbone of JSON payloads, configuration maps, and database row representations. - Multidimensional Arrays: Arrays whose elements are themselves arrays, enabling tabular grids, matrix representations, and hierarchical records (for example, a list of associative student records or a 3x3 numeric matrix). Elements are accessed by chaining bracket indices, such as
$matrix[1][2]or$students[0]['name'].
1.2 Traversing and Manipulating Arrays
The foreach loop is the canonical mechanism for iterating over both indexed and associative arrays without relying on contiguous integer keys. The syntax foreach ($arr as $key => $value) exposes both the key and value on each step. To mutate array elements in place during iteration, prefix the value variable with an ampersand (&$value) and call unset($value) immediately after the loop to release the trailing reference.
1.3 Comprehensive Catalog of Array Functions
PHP provides an extensive standard library of array functions for inspection, stack/queue mutation, slicing, sorting, set operations, and functional transformations.
| Category | Function Signature | Behavior and Practical Use Case |
|---|---|---|
| Inspection | count($arr), in_array($val, $arr, true), array_key_exists($k, $arr) |
Counts elements, checks strict value membership, or verifies whether a key exists even if its value is NULL. |
| Stack & Queue | array_push(), array_pop(), array_shift(), array_unshift() |
Appends or removes elements from the end (LIFO stack) or beginning (FIFO queue) of an array. |
| Slicing & Merging | array_merge($a, $b), array_slice($a, $off, $len), array_splice() |
Combines arrays, extracts non-destructive sub-arrays, or removes/replaces segments in place. |
| Sorting | sort(), rsort(), asort(), ksort(), arsort(), krsort(), usort() |
Sorts indexed arrays (re-indexing keys) or associative arrays while preserving key-value associations (a*), sorting by key (k*), or using custom comparators (usort). |
| Functional | array_map($fn, $arr), array_filter($arr, $fn), array_reduce() |
Transforms every element, selects matching elements, or aggregates an array into a single scalar result. |
| Keys, Values & Sets | array_keys($arr), array_values($arr), array_unique($arr), array_diff() |
Extracts keys/values as indexed lists, removes duplicates, or computes set differences between arrays. |
<?php
$students = [
["name" => "Rohan", "dept" => "BCA", "score" => 78],
["name" => "Meera", "dept" => "BCA", "score" => 94],
["name" => "Karthik", "dept" => "BSc", "score" => 85],
["name" => "Divya", "dept" => "BCA", "score" => 88]
];
// Filter BCA students only
$bcaOnly = array_filter($students, fn($s) => $s['dept'] === 'BCA');
// Sort descending by score using spaceship operator
usort($bcaOnly, fn($a, $b) => $b['score'] <=> $a['score']);
foreach ($bcaOnly as $rank => $st) {
echo "Rank " . ($rank + 1) . ": {$st['name']} ({$st['score']})\n";
}
// Compute average score using array_column and array_sum
$scores = array_column($bcaOnly, 'score');
$avg = array_sum($scores) / count($scores);
echo "BCA Average: " . number_format($avg, 2) . "\n";
?>Chapter 2: String Processing and Date/Time Functions
2.1 String Manipulation, Formatting, and Escaping
Web applications constantly sanitize, parse, and format text. PHP treats strings as mutable byte sequences and offers specialized functions for formatting, searching, slicing, splitting, and security escaping.
- Formatting Functions:
printf()prints a formatted string directly using format specifiers (%sfor string,%dfor signed integer,%for%.2ffor fixed-decimal float,%xfor hexadecimal), whilesprintf()returns the formatted string for assignment.number_format($num, 2, '.', ',')formats numbers with grouped thousands separators. - Length, Case, and Trimming:
strlen($s)returns byte length (usemb_strlen()for UTF-8 multibyte text),strtolower(),strtoupper(),ucfirst(), anducwords()adjust casing, andtrim(),ltrim(),rtrim()strip leading or trailing whitespace or specified character masks. - Searching and Replacing:
strpos($haystack, $needle)locates the zero-based position of a substring (always compare with!== falsebecause index0is valid and falsy in loose comparisons),str_contains($h, $n)tests presence directly,substr($s, $start, $len)extracts a slice, andstr_replace($search, $replace, $subject)substitutes occurrences. - Comparison, Splitting, and Joining:
strcmp($a, $b)and case-insensitivestrcasecmp($a, $b)perform lexicographical comparison.explode($delimiter, $str)splits a delimited string into an array, whereasimplode($glue, $arr)joins array elements back into a single string. - Security Escaping:
htmlspecialchars($str, ENT_QUOTES, 'UTF-8')converts special HTML characters (<,>,&,",') into safe entities to prevent Cross-Site Scripting (XSS) when rendering user-supplied text.
| String Function | Primary Operation | Example Output |
|---|---|---|
trim(" PHP ") |
Removes surrounding whitespace | "PHP" |
substr("UK5DSCCAP300", 0, 6) |
Extracts 6-character prefix | "UK5DSC" |
str_replace(" ", "-", "a b c") |
Replaces spaces with hyphens | "a-b-c" |
explode(",", "A,B,C") |
Splits CSV into indexed array | ["A", "B", "C"] |
sprintf("%04d", 42) |
Zero-pads integer to 4 digits | "0042" |
2.2 Date and Time Functions
PHP represents points in time either as integer Unix timestamps (seconds elapsed since January 1, 1970 00:00:00 UTC) or as object-oriented DateTime instances. Setting the regional timezone with date_default_timezone_set('Asia/Kolkata') ensures consistent local time rendering across servers.
date($format, $timestamp): Formats a Unix timestamp (defaulting to current time) using format tokens:Y(4-digit year),m(zero-padded month),d(zero-padded day),H(24-hour),i(minutes),s(seconds), andl(full weekday name).time()andmktime():time()returns the current Unix timestamp, whilemktime($h, $m, $s, $mon, $day, $yr)constructs a timestamp from explicit calendar components.strtotime($text): Parses natural English date descriptions such as"+7 days","next Monday", or"2026-05-15"into a Unix timestamp.checkdate($month, $day, $year)andgetdate():checkdate()validates whether a Gregorian calendar date actually exists (accounting for leap years), whilegetdate()returns an associative array of date/time parts.DateTimeandDateInterval: Modern object-oriented classes supporting timezone-aware arithmetic, immutable dates (DateTimeImmutable), and exact interval differences via$d1->diff($d2).
<?php
date_default_timezone_set("Asia/Kolkata");
$csvLine = " UK5DSCCAP300 , PHP and MySQL , 4 ";
$parts = array_map("trim", explode(",", $csvLine));
$formatted = sprintf("Code: %s | Title: %s | Credits: %d", $parts[0], $parts[1], (int)$parts[2]);
echo $formatted . "\n";
$isValid = checkdate(2, 29, 2024); // true (leap year)
echo "Feb 29, 2024 valid: " . ($isValid ? "Yes" : "No") . "\n";
$examDate = new DateTime("2026-11-20");
$today = new DateTime("2026-11-01");
$diff = $today->diff($examDate);
echo "Days remaining: " . $diff->days . " days (Formatted: " . $examDate->format("d-M-Y") . ")\n";
?>Chapter 3: Working with Files and Directories
3.1 File Streams, Access Modes, and Sequential I/O
PHP interacts with the server filesystem using C-style stream handles. A file is opened with fopen($filename, $mode), processed with read/write functions, and released with fclose($handle). Choosing the appropriate access mode determines whether existing content is preserved, truncated, or appended.
| Mode | Capabilities | Pointer Position | Behavior if Missing / Existing |
|---|---|---|---|
"r" |
Read only | Beginning of file | Fails with warning if missing; preserves existing data. |
"w" |
Write only | Beginning of file | Creates file if missing; truncates existing content to zero bytes. |
"a" |
Write only (append) | End of file | Creates file if missing; preserves existing data and appends at end. |
"r+" |
Read and write | Beginning of file | Fails if missing; overwrites bytes from the start without truncating. |
"w+" |
Read and write | Beginning of file | Creates file if missing; truncates existing content to zero bytes. |
"x" |
Exclusive create & write | Beginning of file | Creates new file; fails if file already exists (prevents race conditions). |
Once opened, fread($fp, $bytes) reads raw byte chunks, fgets($fp) reads a single line terminated by a newline, fgetcsv($fp) parses comma-separated lines into arrays, and feof($fp) tests whether the end-of-file marker has been reached. For writing, fwrite($fp, $data) writes string bytes and returns the byte count written. For concurrent writes, flock($fp, LOCK_EX) acquires an advisory exclusive lock.
For small files, high-level helpers file_get_contents($path) and file_put_contents($path, $data, FILE_APPEND) perform open, read/write, and close in a single call. File metadata and management helpers include file_exists(), is_file(), filesize(), filemtime(), copy(), rename(), and unlink() (to delete a file).
3.2 Directory Operations
Directories are managed via mkdir($path, 0755, true) to create nested folders recursively, rmdir($path) to remove an empty directory, and is_dir($path) to verify directory status. Listing contents is accomplished either procedurally using opendir(), readdir(), and closedir(), or concisely via scandir($dir), which returns an array of entry names including . and ... Path inspection helpers basename(), dirname(), and pathinfo() extract filename components portably across Windows and Unix separators.
<?php
$logDir = __DIR__ . "/logs";
if (!is_dir($logDir)) {
mkdir($logDir, 0755, true);
}
$logFile = $logDir . "/activity.log";
$entry = date("Y-m-d H:i:s") . " - Module II file I/O verified\n";
file_put_contents($logFile, $entry, FILE_APPEND | LOCK_EX);
$handle = fopen($logFile, "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo htmlspecialchars($line);
}
fclose($handle);
}
// Directory traversal using opendir/readdir
if ($dh = opendir($logDir)) {
while (($item = readdir($dh)) !== false) {
if ($item !== '.' && $item !== '..') {
echo "Found file: $item (" . filesize($logDir . "/" . $item) . " bytes)\n";
}
}
closedir($dh);
}
?>Chapter 4: Object-Oriented Programming (OOP) in PHP
4.1 Classes, Objects, Properties, and Methods
Object-Oriented Programming organizes software around reusable blueprints called classes and runtime instances called objects. A class bundles state (properties) and behavior (methods). Inside an instance method, the pseudo-variable $this refers to the current invoking object instance, enabling access to its own properties and methods via the object operator (->).
Special lifecycle magic methods automate initialization and cleanup: __construct() executes automatically when an object is instantiated via new ClassName(), whereas __destruct() executes when all references to the object are released or the script terminates. Other useful magic methods include __toString() for custom string representation and __get() / __set() for dynamic property interception.
4.2 Encapsulation and Access Modifiers
Encapsulation restricts direct external access to internal state by applying visibility modifiers to properties and methods, ensuring invariants are enforced through controlled getter and setter methods:
public: Accessible from anywhere — outside the class, inside the class, and within subclasses.protected: Accessible only within the declaring class and any classes that inherit from it.private: Strictly accessible only within the declaring class itself; hidden from both external callers and child classes.
4.3 Inheritance, Polymorphism, Abstract Classes, Interfaces, and Traits
Inheritance allows a child class to reuse and extend a parent class using the extends keyword. PHP supports single class inheritance: each class may extend at most one direct parent. A child class can override a parent method to specialize behavior (runtime polymorphism) and invoke the parent's implementation using parent::methodName(). Marking a class or method as final prevents further inheritance or overriding.
Abstract classes (abstract class Shape) cannot be instantiated directly and may combine concrete methods with abstract method signatures that subclasses must implement. Interfaces (interface Authenticatable) define pure behavioral contracts consisting of public method signatures that unrelated classes can adopt via implements, supporting multiple interface implementation. Traits (trait Timestampable) enable horizontal code reuse across unrelated classes via use Timestampable;. Static properties and methods belong to the class itself rather than any instance and are accessed using the scope resolution operator (ClassName::method() or self::$prop).
<?php
interface Printable {
public function formatSummary(): string;
}
abstract class AcademicEntity {
protected string $code;
public function __construct(string $code) {
$this->code = $code;
}
abstract public function getRole(): string;
}
class Course extends AcademicEntity implements Printable {
private string $title;
private static int $totalCourses = 0;
public function __construct(string $code, string $title) {
parent::__construct($code);
$this->title = $title;
self::$totalCourses++;
}
public function getRole(): string {
return "Core Discipline Course";
}
public function formatSummary(): string {
return "[{$this->code}] {$this->title} (" . $this->getRole() . ")";
}
public static function getCount(): int {
return self::$totalCourses;
}
}
$phpCourse = new Course("UK5DSCCAP300", "PHP and MySQL");
echo $phpCourse->formatSummary() . "\n";
echo "Total Courses Created: " . Course::getCount() . "\n";
?>Chapter 5: Advanced OOP Design Patterns and Standard Interfaces
5.1 Constructor Property Promotion, Readonly Properties, and Cloning
Modern PHP streamlines class boilerplate through constructor property promotion, allowing visibility modifiers directly inside the __construct() parameter list so properties are declared and assigned simultaneously. Declaring a property readonly enforces immutability after initialization, guaranteeing that value objects cannot be mutated accidentally.
Assigning an object variable ($b = $a;) copies only the object handle, meaning both variables point to the same underlying instance in memory. Creating an independent copy requires the clone keyword ($b = clone $a;), which triggers the __clone() magic method so nested object references can be deep-copied cleanly. Type checking at runtime uses the instanceof operator to verify whether an object belongs to a specific class or implements a given interface.
5.2 Late Static Binding and Built-In SPL Interfaces
In inheritance hierarchies, self:: resolves to the class where the method was lexically defined, whereas static:: (Late Static Binding) resolves to the runtime class on which the method was actually invoked. This enables inherited factory methods to instantiate subclasses accurately.
PHP's Standard PHP Library (SPL) defines built-in interfaces that integrate custom classes seamlessly with native language constructs:
Countable: Implementingcount(): intallows an object to be passed directly to PHP's built-incount($obj)function.JsonSerializable: ImplementingjsonSerialize(): mixedcustomizes the payload emitted when an object is passed tojson_encode().IteratorAggregate: ImplementinggetIterator(): Traversableenables directforeach ($collection as $item)traversal over encapsulated object collections.
<?php
class BookItem implements JsonSerializable {
public function __construct(
public readonly string $isbn,
public readonly string $title,
private float $price
) {}
public function getPrice(): float {
return $this->price;
}
public function jsonSerialize(): array {
return ['isbn' => $this->isbn, 'title' => $this->title, 'price' => $this->price];
}
}
class LibraryShelf implements Countable, IteratorAggregate {
private array $books = [];
public function add(BookItem $book): void {
$this->books[] = $book;
}
public function count(): int {
return count($this->books);
}
public function getIterator(): Traversable {
return new ArrayIterator($this->books);
}
}
$shelf = new LibraryShelf();
$shelf->add(new BookItem("978-01", "PHP Architecture", 495.00));
$shelf->add(new BookItem("978-02", "MySQL Internals", 550.00));
echo "Books on shelf: " . count($shelf) . "\n";
foreach ($shelf as $b) {
echo json_encode($b) . "\n";
}
?>Chapter 6: Integrated Array, String, File, and OOP Walkthroughs
6.1 Building a CSV Roster Analyzer with Persistent Reporting
Real-world PHP batch scripts frequently combine Module II concepts: reading structured CSV files from disk, parsing and normalizing strings, aggregating multidimensional arrays, and writing formatted summary reports back to the filesystem. Consider a student attendance CSV containing rows of RollNo,Name,PresentDays,TotalDays.
To compute percentage attendance accurately, the script applies:
Worked Numerical Example: If a student attended Dp = 68 days out of Dt = 80 working days, then A% = (68 / 80) × 100 = 0.85 × 100 = 85.00%, which satisfies a 75% eligibility threshold.
6.2 Recursive Directory Scanner and File Size Auditor
When managing user uploads or log archives, administrators often need to audit nested directories recursively. Using scandir() combined with is_dir() and recursion traverses arbitrarily deep folder trees, accumulating total byte counts and formatting human-readable sizes using number_format().
<?php
class AttendanceReport {
private array $records = [];
public function loadCsv(string $csvPath): void {
if (!file_exists($csvPath)) {
throw new RuntimeException("CSV file not found: $csvPath");
}
$fp = fopen($csvPath, "r");
$header = fgetcsv($fp); // Skip header row
while (($row = fgetcsv($fp)) !== false) {
if (count($row) < 4) continue;
$present = (int) trim($row[2]);
$total = max(1, (int) trim($row[3]));
$pct = ($present / $total) * 100;
$this->records[] = [
'roll' => trim($row[0]),
'name' => ucwords(strtolower(trim($row[1]))),
'pct' => round($pct, 2),
'eligible' => $pct >= 75.0
];
}
fclose($fp);
}
public function exportSummary(string $outPath): void {
$lines = ["ROLL | NAME | ATTENDANCE | STATUS"];
foreach ($this->records as $r) {
$status = $r['eligible'] ? "ELIGIBLE" : "SHORTAGE";
$lines[] = sprintf("%-6s | %-18s | %6.2f%% | %s", $r['roll'], $r['name'], $r['pct'], $status);
}
file_put_contents($outPath, implode(PHP_EOL, $lines) . PHP_EOL);
}
}
function getDirectorySize(string $dir): int {
$totalBytes = 0;
foreach (scandir($dir) as $entry) {
if ($entry === '.' || $entry === '..') continue;
$full = $dir . DIRECTORY_SEPARATOR . $entry;
$totalBytes += is_dir($full) ? getDirectorySize($full) : filesize($full);
}
return $totalBytes;
}
?>Chapter 7: Regular Expressions and JSON Serialization in PHP
7.1 Pattern Matching with PCRE Functions
While basic string functions handle fixed substrings, complex pattern validation—such as verifying Indian postal codes, course codes (UK5DSCCAP300), or extracting structured tokens from log files—relies on Perl-Compatible Regular Expressions (PCRE). PHP exposes three core PCRE functions:
preg_match($pattern, $subject, $matches): Searches for the first match of$patterninside$subject, returning1if found,0if not found, orfalseon syntax error. Captured parenthesized groups populate$matches[1],$matches[2], and so on.preg_match_all($pattern, $subject, $matches): Finds every non-overlapping match across the entire string, useful for extracting all hashtags, email addresses, or hyperlinks from a document.preg_replace($pattern, $replacement, $subject): Substitutes all pattern matches with a replacement string or callback result, commonly used to sanitize slugs or mask sensitive digits.
7.2 JSON Serialization for Web APIs and Data Storage
Associative and multidimensional arrays frequently serve as data-transfer structures between PHP backends and JavaScript frontends or disk-based configuration files. json_encode($data, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR) serializes arrays and JsonSerializable objects into standard JSON text, while json_decode($json, true) parses JSON strings back into PHP associative arrays (passing true for the second argument ensures objects decode as associative arrays rather than stdClass instances).
<?php
function validateCourseCode(string $code): bool {
return preg_match('/^UK[1-8][A-Z]{3}[A-Z]{3}\d{3}$/', $code) === 1;
}
$courses = [
["code" => "UK5DSCCAP300", "title" => "PHP and MySQL", "credits" => 4],
["code" => "UK5DSCCAP301", "title" => "Software Engineering", "credits" => 4]
];
foreach ($courses as $c) {
$valid = validateCourseCode($c['code']) ? "VALID" : "INVALID";
echo "{$c['code']} -> $valid\n";
}
$jsonPayload = json_encode($courses, JSON_PRETTY_PRINT);
file_put_contents(__DIR__ . "/courses.json", $jsonPayload);
$reloaded = json_decode(file_get_contents(__DIR__ . "/courses.json"), true);
echo "Reloaded first course: " . $reloaded[0]['title'] . "\n";
?>Module III: Forms, State Management, and Images
Chapter 1: HTML Forms, Input Arrays, and Self-Processing Scripts
1.1 Form Submission Mechanics: GET vs. POST
HTML forms collect structured input from users and transmit it to a server-side PHP script specified by the action attribute using the HTTP method declared in method. Choosing between GET and POST affects visibility, payload capacity, bookmarking, and idempotency.
| Feature | HTTP GET ($_GET) |
HTTP POST ($_POST) |
|---|---|---|
| Data Transport | Appended to URL as a query string (?key=value&...). |
Encoded inside the HTTP request body (invisible in URL bar). |
| Size Limit | Restricted by browser/server URL length limits (~2,048 characters). | Large payloads supported (configured via post_max_size in php.ini). |
| Binary & Files | Supports ASCII/URL-encoded text only; cannot upload files. | Supports binary file uploads when enctype="multipart/form-data" is set. |
| Security & Caching | Visible in browser history and server logs; cacheable and bookmarkable. | Not stored in browser history or URL logs; required for passwords and state writes. |
1.2 Accessing Form Input with User-Defined Arrays
When a form presents multiple checkboxes, multi-select dropdowns, or dynamic rows sharing the same logical field, appending empty square brackets to the HTML name attribute (for example, name="skills[]") instructs PHP to automatically assemble all checked values into an indexed array inside $_POST['skills']. Associative keys can also be specified directly in HTML, such as name="student[email]" and name="student[phone]", which PHP parses into a nested associative array.
1.3 Combining HTML and PHP Code on a Single Script
Rather than splitting a form and its handler across two separate files, a self-processing script posts back to itself. The form's action attribute uses htmlspecialchars($_SERVER['PHP_SELF']) to prevent URL-based XSS injection. Inside the script, checking if ($_SERVER['REQUEST_METHOD'] === 'POST') distinguishes an initial page load from a submitted form, enabling sticky form values (re-populating valid fields when another field fails validation) and inline error reporting.
1.4 Hidden Fields, Redirects, and Sending Mail
Using Hidden Fields to Save State: Hidden input fields (<input type="hidden" name="step" value="2">) embed non-editable state tokens, wizard step numbers, or record identifiers inside an HTML form so they travel back to the server on submission. Because users can inspect and alter hidden fields via browser developer tools, sensitive values like prices or user roles must never trust hidden fields without server-side verification.
Redirecting the User: After processing a POST submission, issuing header("Location: thankyou.php"); exit(); implements the Post/Redirect/Get (PRG) pattern, preventing duplicate database inserts if the user refreshes the browser. Because HTTP headers precede body content, header() must be called before any HTML or whitespace is echoed, and exit() must follow immediately to halt further script execution.
Sending Mail on Form Submission: PHP's built-in mail($to, $subject, $message, $headers) dispatches email through the server's configured Mail Transfer Agent (MTA) or SMTP relay. Input fields used in mail headers (such as Reply-To) must be stripped of newline characters (\r, \n) to prevent header injection attacks. Creating a contact workflow involves two components: the HTML form capturing sender name, email, subject, and message, and the PHP handler validating inputs, sanitizing headers, and invoking mail().
<?php
$errors = [];
$name = "";
$email = "";
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = trim($_POST['student_name'] ?? '');
$email = filter_var(trim($_POST['email'] ?? ''), FILTER_VALIDATE_EMAIL);
$skills = $_POST['skills'] ?? [];
$formVersion = $_POST['form_version'] ?? '1.0';
if ($name === '') {
$errors[] = "Student name is required.";
}
if (!$email) {
$errors[] = "A valid email address is required.";
}
if (empty($errors)) {
$to = "[email protected]";
$subject = "New Registration (v" . preg_replace('/[^0-9.]/', '', $formVersion) . ")";
$body = "Name: $name\nSkills: " . implode(", ", array_map('htmlspecialchars', $skills));
$headers = "From: [email protected]\r\nReply-To: " . str_replace(["\r", "\n"], "", $email);
@mail($to, $subject, $body, $headers);
header("Location: success.php?user=" . urlencode($name));
exit();
}
}
?>
<form method="POST" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">
<input type="hidden" name="form_version" value="2.0">
<label>Name: <input type="text" name="student_name" value="<?= htmlspecialchars($name) ?>"></label><br>
<label>Email: <input type="email" name="email" value="<?= htmlspecialchars($email ?: '') ?>"></label><br>
<label><input type="checkbox" name="skills[]" value="PHP"> PHP</label>
<label><input type="checkbox" name="skills[]" value="MySQL"> MySQL</label><br>
<button type="submit">Register</button>
</form>Chapter 2: Concepts of File Uploads in PHP
2.1 Multipart Encoding and the $_FILES Superglobal
Uploading files requires an HTML form configured with method="POST" and enctype="multipart/form-data". Standard URL encoding cannot transmit raw binary files efficiently; multipart encoding splits each form field and binary file into boundary-delimited parts. When submitted, the web server writes the uploaded binary payload to a temporary directory and populates $_FILES['field_name'] with five metadata keys:
name: Original filename reported by the client browser.type: MIME type reported by the client browser (for example,image/png; easily spoofed).tmp_name: Temporary absolute path on the server where PHP stored the uploaded file.error: Integer status code indicating upload outcome (UPLOAD_ERR_OK= 0,UPLOAD_ERR_INI_SIZE= 1,UPLOAD_ERR_FORM_SIZE= 2,UPLOAD_ERR_NO_FILE= 4).size: File size in bytes.
2.2 Security Validation and Safe Persistence
Never trust client-supplied filenames or MIME types. Secure upload handlers verify error === UPLOAD_ERR_OK, enforce a maximum byte threshold (also bounded by upload_max_filesize and post_max_size in php.ini), inspect the true MIME type from file magic bytes using finfo_file(), generate a unique server-side filename (using bin2hex(random_bytes(8)) or uniqid()), and move the file from temporary storage using move_uploaded_file($tmp, $dest), which verifies that the source was genuinely uploaded via HTTP POST.
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['avatar'])) {
$file = $_FILES['avatar'];
$allowedExt = ['jpg', 'jpeg', 'png'];
$allowedMime = ['image/jpeg', 'image/png'];
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if ($file['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code: " . $file['error']);
}
if ($file['size'] > 2 * 1024 * 1024) {
die("File exceeds 2 MB limit.");
}
if (!in_array($ext, $allowedExt, true)) {
die("Invalid file extension.");
}
$finfo = new finfo(FILEINFO_MIME_TYPE);
$trueMime = $finfo->file($file['tmp_name']);
if (!in_array($trueMime, $allowedMime, true)) {
die("Invalid binary file content.");
}
$safeName = bin2hex(random_bytes(8)) . "." . $ext;
$targetPath = __DIR__ . "/uploads/" . $safeName;
if (move_uploaded_file($file['tmp_name'], $targetPath)) {
echo "Uploaded securely as " . htmlspecialchars($safeName);
}
}
?>Chapter 3: Cookies and Session Management
3.1 Cookies: Types, Lifecycle, and PHP API
Because HTTP is inherently stateless, cookies provide a mechanism for storing small key-value pairs (up to ~4 KB) on the client browser, which automatically returns them with every subsequent request to the matching domain and path.
- Session Cookies vs. Persistent Cookies: Session cookies omit an expiration timestamp (
0) and are deleted automatically when the browser closes. Persistent cookies specify a future Unix timestamp and survive browser restarts until expiration or manual clearing. - First-Party vs. Third-Party Cookies: First-party cookies are set by the visited domain, whereas third-party cookies originate from embedded external domains (such as analytics or advertising scripts).
- Security Attributes:
HttpOnlyblocks client-side JavaScript (document.cookie) from reading the cookie, mitigating XSS token theft;Securerestricts transmission to encrypted HTTPS connections; andSameSite(LaxorStrict) mitigates Cross-Site Request Forgery (CSRF). - Setting and Deleting Cookies:
setcookie($name, $value, $expires, $path, $domain, $secure, $httponly)sends aSet-CookieHTTP response header and must therefore be invoked before any HTML output. Reading a cookie uses$_COOKIE[$name](available on the next request). Deleting a cookie requires callingsetcookie()with the same name and path and an expiration timestamp in the past (such astime() - 3600).
3.2 Sessions: Server-Side State Management
Sessions overcome cookie size limits and client-side tampering by storing user data on the server while issuing only a random opaque identifier (such as PHPSESSID) to the client. Calling session_start() at the top of a script either creates a new session or resumes an existing one by loading serialized data into $_SESSION.
- Working with Session Variables: Values are stored and read like any associative array:
$_SESSION['user_id'] = 105;and$_SESSION['role'] = 'student';. - Passing Session IDs in the Query String: When a client disables cookies, PHP can propagate the session ID via URL query parameters using the built-in
SIDconstant (for example,<a href="next.php?<?= htmlspecialchars(SID) ?>">) or explicitly viasession_id(). Because URL session IDs risk leakage through browser history andRefererheaders, cookie-based transport withsession.use_only_cookies = 1is preferred in production. - Unsetting Variables and Destroying Sessions: Individual keys are removed via
unset($_SESSION['cart']). A complete logout clears all session variables using$_SESSION = []orsession_unset(), expires the session cookie on the client, and deletes the server-side session file viasession_destroy().
<?php
// Setting a persistent HttpOnly cookie for 7 days
setcookie("theme_pref", "classic", [
'expires' => time() + (7 * 86400),
'path' => '/',
'secure' => false,
'httponly' => true,
'samesite' => 'Lax'
]);
// Deleting a cookie by setting past expiration
// setcookie("theme_pref", "", time() - 3600, "/");
session_start();
if (!isset($_SESSION['visits'])) {
$_SESSION['visits'] = 1;
} else {
$_SESSION['visits']++;
}
echo "Active Session ID: " . session_id() . " | Visits: " . $_SESSION['visits'] . "\n";
// Complete logout / destruction sequence:
// $_SESSION = [];
// session_unset();
// if (ini_get("session.use_cookies")) {
// $params = session_get_cookie_params();
// setcookie(session_name(), '', time() - 42000, $params['path'], $params['domain']);
// }
// session_destroy();
?>Chapter 4: Working with Images Using the PHP GD Library
4.1 The GD Graphics Pipeline and Core Functions
PHP's GD (Graphics Draw) extension enables server-side creation and manipulation of PNG, JPEG, GIF, and WebP images for tasks such as dynamic thumbnails, watermarks, charts, and CAPTCHA verification badges. Every GD script follows a four-step pipeline: allocate an image canvas, define colors, draw primitives or text, and stream the binary image with the proper Content-Type header before freeing memory.
| GD Function | Purpose | Key Parameters |
|---|---|---|
imagecreatetruecolor($w, $h) |
Allocates a blank 24-bit RGB canvas | Width and height in pixels |
imagecolorallocate($img, $r, $g, $b) |
Registers an RGB color for drawing | Image resource and 0–255 RGB channels |
imagefilledrectangle() / imagerectangle() |
Draws solid or outlined rectangles | Canvas, top-left (x1, y1), bottom-right (x2, y2), color |
imageline() / imageellipse() |
Draws straight lines and ellipses | Coordinates, radii, and allocated color |
imagestring() / imagettftext() |
Renders built-in bitmap or TrueType text | Font size/file, coordinates, text string, color |
imagepng() / imagejpeg() |
Outputs binary image to browser or file | Canvas and optional destination path/quality |
imagedestroy($img) |
Frees memory allocated to the canvas | Image resource handle |
<?php
header("Content-Type: image/png");
$width = 260;
$height = 80;
$img = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($img, 245, 247, 250);
$navy = imagecolorallocate($img, 31, 58, 95);
$border = imagecolorallocate($img, 180, 190, 205);
$accent = imagecolorallocate($img, 100, 116, 139);
imagefilledrectangle($img, 0, 0, $width - 1, $height - 1, $bgColor);
imagerectangle($img, 0, 0, $width - 1, $height - 1, $border);
imageline($img, 16, 56, 244, 56, $navy);
imagestring($img, 5, 34, 20, "PHP-GD VERIFIED", $navy);
imagestring($img, 2, 72, 60, "UK5DSCCAP300", $accent);
imagepng($img);
imagedestroy($img);
?>Chapter 5: Form Validation, Sanitization, and Web Security Defenses
5.1 Server-Side Validation with filter_var() and filter_input()
Client-side HTML5 attributes such as required, type="email", and maxlength improve usability, yet they can be bypassed trivially via browser developer tools or direct HTTP requests. Consequently, authoritative validation and sanitization must always execute on the server in PHP. The built-in Filter extension provides standardized, tested validators and sanitizers:
- Validation Filters: Return the validated value on success or
falseon failure without modifying input. Key flags includeFILTER_VALIDATE_EMAIL,FILTER_VALIDATE_INT(supportingmin_rangeandmax_rangeoptions),FILTER_VALIDATE_FLOAT,FILTER_VALIDATE_URL, andFILTER_VALIDATE_IP. - Sanitization Filters: Strip or encode unwanted characters before storage or processing, such as
FILTER_SANITIZE_EMAIL,FILTER_SANITIZE_NUMBER_INT, andFILTER_SANITIZE_URL. - Direct Superglobal Filtering:
filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT)safely reads and validates a field without triggering missing-key warnings.
5.2 Defending Against XSS, CSRF, and Header Injection
Forms are the primary attack surface of web applications. Three mandatory defenses protect form-driven PHP scripts:
- Cross-Site Scripting (XSS) Prevention: Always encode dynamic output before rendering in HTML using
htmlspecialchars($str, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'). This neutralizes injected<script>tags and event handlers. - Cross-Site Request Forgery (CSRF) Protection: Generate a cryptographically random token stored in
$_SESSION['csrf_token']viabin2hex(random_bytes(32)), embed it as a hidden form field, and verify it on POST submission using constant-time comparisonhash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? ''). - Email Header Injection Defense: When passing form fields into
mail()headers, reject or strip\rand\ncharacters to block attackers from injecting arbitraryBcc:recipients.
| Mail Mechanism | Transport | Strengths & Limitations |
|---|---|---|
Built-in mail() |
Local Sendmail / MTA binary | Zero external dependencies; limited error diagnostics and lacks native SMTP authentication/TLS. |
| SMTP Libraries (e.g., PHPMailer) | Direct authenticated SMTP over TLS | Supports HTML attachments, DKIM signing, detailed debug logs, and reliable cloud relay delivery. |
<?php
session_start();
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$status = "";
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$submittedToken = $_POST['csrf_token'] ?? '';
if (!hash_equals($_SESSION['csrf_token'], $submittedToken)) {
http_response_code(403);
die("Invalid CSRF token.");
}
$age = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT, [
'options' => ['min_range' => 16, 'max_range' => 100]
]);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($age === false || $email === false) {
$status = "Please enter a valid age (16-100) and email address.";
} else {
$status = "Validated: " . htmlspecialchars($email) . " (Age: $age)";
}
}
?>Chapter 6: Advanced GD Image Processing and Session Security
6.1 Dynamic CAPTCHA Generation and Image Resampling
Beyond simple badges, GD powers two high-value web features: anti-bot CAPTCHA challenges and proportional thumbnail generation. A CAPTCHA script generates a random alphanumeric string, stores it in $_SESSION['captcha_code'], draws distorted noise lines and random pixels onto a GD canvas, renders the code with imagestring() or TrueType fonts, and verifies the user's form submission against the session value.
For uploaded photos, imagecreatefromjpeg() or imagecreatefrompng() loads the source image, getimagesize() inspects original dimensions, and imagecopyresampled() smoothly scales the image onto a smaller destination canvas while preserving aspect ratio.
6.2 Session Fixation, Timeout, and Storage Configuration
Default PHP sessions store serialized key-value files in the directory specified by session.save_path. To harden session security in production:
- Prevent Session Fixation: Always invoke
session_regenerate_id(true)immediately after a user authenticates or elevates privileges, replacing any pre-login session identifier. - Enforce Idle Timeouts: Store
$_SESSION['last_activity'] = time()on each request and destroy the session if inactivity exceeds a threshold (for example, 1,800 seconds). - Cookie Hardening: Configure
session.cookie_httponly = 1andsession.use_strict_mode = 1so PHP rejects uninitialized session IDs supplied by attackers.
<?php
function createThumbnail(string $srcPath, string $destPath, int $maxWidth): bool {
[$origW, $origH, $type] = getimagesize($srcPath);
$ratio = $origH / $origW;
$newW = min($maxWidth, $origW);
$newH = (int) round($newW * $ratio);
$srcImg = ($type === IMAGETYPE_PNG) ? imagecreatefrompng($srcPath) : imagecreatefromjpeg($srcPath);
$thumb = imagecreatetruecolor($newW, $newH);
imagecopyresampled($thumb, $srcImg, 0, 0, 0, 0, $newW, $newH, $origW, $origH);
$ok = imagejpeg($thumb, $destPath, 85);
imagedestroy($srcImg);
imagedestroy($thumb);
return $ok;
}
function enforceSessionTimeout(int $maxIdleSeconds = 1800): void {
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > $maxIdleSeconds) {
$_SESSION = [];
session_unset();
session_destroy();
header("Location: login.php?timeout=1");
exit();
}
$_SESSION['last_activity'] = time();
}
?>Chapter 7: Multi-Step Wizards, Flash Messaging, and Watermarking
7.1 Preserving State Across Multi-Step Forms
Long registration or checkout workflows are often split across multiple sequential screens to reduce cognitive load. Developers choose between two state-preservation strategies depending on security and lifecycle requirements:
- Hidden Fields for Non-Sensitive Step State: Passing step numbers or temporary wizard tokens via
<input type="hidden">keeps server memory light, but requires re-validating every accumulated field on the final step because hidden inputs remain user-editable in the browser DOM. - Session-Backed Wizard Buffers: Storing intermediate step payloads inside
$_SESSION['wizard']['step1']keeps form data strictly on the server, prevents tampering between steps, and allows users to navigate backward and forward without losing previously validated inputs.
7.2 Session Flash Messages and GD Image Watermarking
When a script uses the Post/Redirect/Get pattern, local PHP variables are wiped on the redirect. A flash message solves this by storing a short status string in $_SESSION['flash_msg'] before header("Location: ..."); the destination script reads, displays, and immediately deletes the key using unset($_SESSION['flash_msg']) so it appears exactly once.
In media-heavy portals, uploaded JPEG or PNG images can be branded automatically using GD watermarking. By loading the uploaded photo with imagecreatefromjpeg(), allocating a semi-transparent color via imagecolorallocatealpha($img, 255, 255, 255, 60), and drawing text or a small PNG stamp with imagecopy() before saving, the server embeds ownership attribution directly into the stored image file.
<?php
function setFlash(string $key, string $message): void {
if (session_status() === PHP_SESSION_NONE) session_start();
$_SESSION['flash'][$key] = $message;
}
function consumeFlash(string $key): ?string {
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['flash'][$key])) return null;
$msg = $_SESSION['flash'][$key];
unset($_SESSION['flash'][$key]);
return $msg;
}
function applyTextWatermark(string $srcJpeg, string $destJpeg, string $label): bool {
$img = imagecreatefromjpeg($srcJpeg);
if (!$img) return false;
$w = imagesx($img);
$h = imagesy($img);
$alphaWhite = imagecolorallocatealpha($img, 255, 255, 255, 45);
$shadow = imagecolorallocatealpha($img, 0, 0, 0, 60);
imagestring($img, 5, $w - 181, $h - 29, $label, $shadow);
imagestring($img, 5, $w - 180, $h - 30, $label, $alphaWhite);
$saved = imagejpeg($img, $destJpeg, 90);
imagedestroy($img);
return $saved;
}
?>Chapter 8: Complete Form, Cookie, Session, and Upload Integration Case Study
8.1 End-to-End Profile Settings Controller
In real-world PHP applications, forms, cookies, sessions, redirects, and file uploads operate together in a unified request lifecycle. Consider a student profile settings screen that allows an authenticated user to update their display theme (stored in a persistent cookie), upload a profile avatar (validated via $_FILES), and receive a one-time confirmation banner (stored in $_SESSION['flash']).
When the user submits the form via POST, the controller first verifies that $_SESSION['user_id'] is active. Next, it validates the uploaded avatar's error flag, size, extension, and binary MIME type before calling move_uploaded_file(). Simultaneously, it writes the selected theme preference cookie with httponly and samesite attributes, records a flash message in the session, and terminates with a header("Location: profile.php") redirect so refreshing the browser never re-uploads the file.
<?php
session_start();
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit();
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$theme = ($_POST['theme'] ?? 'light') === 'dark' ? 'dark' : 'light';
setcookie("ui_theme", $theme, time() + (30 * 86400), "/", "", false, true);
if (isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
$ext = strtolower(pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION));
if (in_array($ext, ['jpg', 'png'], true) && $_FILES['photo']['size'] <= 1048576) {
$dest = __DIR__ . "/avatars/user_" . (int)$_SESSION['user_id'] . "." . $ext;
move_uploaded_file($_FILES['photo']['tmp_name'], $dest);
}
}
$_SESSION['flash_notice'] = "Profile preferences saved.";
header("Location: profile.php");
exit();
}
?>Module IV: MySQL and PHP-MySQL Integration
Chapter 1: Relational Database Concepts and MySQL Architecture
1.1 Open-Source Database Software and MySQL Features
MySQL is the world's most widely adopted open-source Relational Database Management System (RDBMS), organizing data into structured tables composed of rows (tuples) and columns (attributes) linked by keys. Operating in a client-server architecture, the MySQL daemon (mysqld) manages concurrent connections, query parsing, optimization, and durable disk storage.
- Pluggable Storage Engines: Supports InnoDB (the default engine providing full ACID transactions—Atomicity, Consistency, Isolation, Durability—row-level locking, and foreign key referential integrity) alongside specialized engines such as MyISAM and Memory.
- Performance and Scalability: Employs B-tree indexing, buffer pools, and query execution optimizers to handle high-throughput web workloads efficiently.
- Cross-Platform & Security: Runs across Linux, Windows, and macOS with granular privilege control (
GRANT/REVOKE), TLS encryption, and standard SQL compliance. - Administration Tools: Managed via the
mysqlcommand-line client or web-based graphical tools such as phpMyAdmin bundled in XAMPP/WAMP.
1.2 MySQL Data Types
Selecting exact column data types minimizes storage footprint, accelerates index lookups, and enforces domain integrity at the database layer.
| Category | MySQL Data Types | Storage & Practical Application |
|---|---|---|
| Numeric | TINYINT, INT, BIGINT, FLOAT, DOUBLE, DECIMAL(M,D) |
INT (4 bytes) for IDs and counts; TINYINT(1) for boolean flags; DECIMAL(10,2) for exact monetary amounts without floating-point rounding errors. |
| Date & Time | DATE, TIME, DATETIME, TIMESTAMP, YEAR |
DATE (YYYY-MM-DD), DATETIME (YYYY-MM-DD HH:MM:SS), and TIMESTAMP (UTC-aware auto-updating audit stamps). |
| String | CHAR(N), VARCHAR(N), TEXT, ENUM, SET |
CHAR for fixed-length codes (e.g., CHAR(12)); VARCHAR for variable names/emails; TEXT for long articles; ENUM for single-choice lists; SET for multi-choice flags. |
Chapter 2: SQL Table Creation, Querying, and Multi-Table Joins
2.1 DDL and Single-Table DML Operations
Data Definition Language (DDL) statements define schemas and constraints. A PRIMARY KEY uniquely identifies each row and is commonly paired with AUTO_INCREMENT. A FOREIGN KEY enforces parent-child referential integrity between tables, while NOT NULL, UNIQUE, and DEFAULT constrain column values. ALTER TABLE modifies existing schemas and DROP TABLE removes tables.
Data Manipulation Language (DML) statements insert, retrieve, filter, and sort records:
INSERT INTO: Adds one or more rows to a table specifying target columns and values.SELECT ... FROM ... WHERE: Projects columns and filters rows using comparison operators (=,<>,>,BETWEEN,IN,IS NULL) and logical connectives (AND,OR,NOT).ORDER BY,DISTINCT, andLIMIT: Sorts result sets in ascending (ASC) or descending (DESC) order, eliminates duplicate rows, and restricts returned row counts for pagination.LIKEOperator: Performs wildcard pattern matching using%(matches zero or more characters) and_(matches exactly one character).- Aggregation: Functions
COUNT(),SUM(),AVG(),MIN(), andMAX()combine withGROUP BYandHAVINGto summarize grouped records.
CREATE DATABASE IF NOT EXISTS college_db;
USE college_db;
CREATE TABLE departments (
dept_id INT AUTO_INCREMENT PRIMARY KEY,
dept_name VARCHAR(80) NOT NULL UNIQUE
) ENGINE=InnoDB;
CREATE TABLE students (
student_id INT AUTO_INCREMENT PRIMARY KEY,
full_name VARCHAR(100) NOT NULL,
email VARCHAR(120) NOT NULL UNIQUE,
dept_id INT NOT NULL,
admission_date DATE NOT NULL,
cgpa DECIMAL(4,2) DEFAULT 0.00,
FOREIGN KEY (dept_id) REFERENCES departments(dept_id)
ON UPDATE CASCADE ON DELETE RESTRICT
) ENGINE=InnoDB;
INSERT INTO departments (dept_name) VALUES ('Computer Applications'), ('Computer Science');
INSERT INTO students (full_name, email, dept_id, admission_date, cgpa)
VALUES ('Aditi Nair', '[email protected]', 1, '2024-07-15', 8.75),
('Vishnu Raj', '[email protected]', 1, '2024-07-18', 9.10),
('Meenakshi S', '[email protected]', 2, '2024-07-20', 8.40);
SELECT full_name, cgpa FROM students
WHERE full_name LIKE 'A%' AND cgpa >= 8.00
ORDER BY cgpa DESC LIMIT 10;2.2 Selecting Multiple Tables Using Joins and Subqueries
Normalized relational schemas distribute entities across multiple tables to eliminate data redundancy and update anomalies. Recombining related rows at query time uses SQL JOIN clauses or nested subqueries:
| Join Type | Matching Semantics | Typical Scenario |
|---|---|---|
INNER JOIN |
Returns only rows where the join condition matches in both tables. | Listing students alongside their assigned department name. |
LEFT JOIN |
Returns all rows from the left table and matched rows from the right (NULL if unmatched). |
Listing all departments including newly created ones with zero students. |
RIGHT JOIN |
Returns all rows from the right table and matched rows from the left. | Auditing right-side master records against optional child rows. |
CROSS JOIN |
Produces the Cartesian product of both tables (every row paired with every row). | Generating schedule grids or size-color product matrices. |
Chapter 3: Modifying Records and MySQL Date/Time Functions
3.1 UPDATE, REPLACE, and DELETE Commands
Existing records are modified or removed using targeted DML commands. Always include a precise WHERE clause with UPDATE and DELETE to avoid altering every row in the table.
UPDATE: Modifies specified columns in existing rows matching theWHEREcondition (for example,UPDATE students SET cgpa = 9.25 WHERE student_id = 2;).REPLACE INTO: A MySQL extension to standard SQL that attempts an insert; if aPRIMARY KEYorUNIQUEconflict occurs, MySQL automatically deletes the conflicting old row and inserts the new row in its place. Note that omitted columns reset to their default values because the old row is replaced rather than patched.DELETE FROM: Removes specific rows matching a condition while logging each deletion for transaction rollback. By contrast,TRUNCATE TABLEdrops and recreates an empty table rapidly without row-level logging and resetsAUTO_INCREMENTcounters.
3.2 Date and Time Functions in MySQL
MySQL provides native temporal functions for server-side filtering, formatting, and interval arithmetic:
- Current Timestamps:
NOW()returns current date and time;CURDATE()returns current date;CURTIME()returns current time. - Formatting & Extraction:
DATE_FORMAT(col, '%d-%m-%Y')formats dates using pattern specifiers;YEAR(),MONTH(),DAY(), andDAYNAME()extract calendar components. - Arithmetic:
DATEDIFF(d1, d2)calculates days between two dates;DATE_ADD(col, INTERVAL 30 DAY)andDATE_SUB()advance or rewind dates by intervals.
SELECT s.student_id, s.full_name, d.dept_name,
DATE_FORMAT(s.admission_date, '%d %b %Y') AS joined_on,
DATEDIFF(CURDATE(), s.admission_date) AS days_enrolled
FROM students s
INNER JOIN departments d ON s.dept_id = d.dept_id
WHERE YEAR(s.admission_date) >= 2024
ORDER BY s.full_name ASC;
UPDATE students SET cgpa = 9.20 WHERE student_id = 2;
REPLACE INTO departments (dept_id, dept_name) VALUES (1, 'BCA & Computer Applications');
DELETE FROM students WHERE cgpa < 4.00;Chapter 4: Interacting with MySQL Using PHP
4.1 Connection Drivers: MySQLi and PDO
PHP communicates with MySQL through two modern extensions: MySQLi (MySQL Improved, supporting both procedural and object-oriented APIs) and PDO (PHP Data Objects, an object-oriented abstraction layer supporting 12+ database engines). The legacy mysql_* extension was removed in PHP 7.0 and must never be used.
4.2 Connecting, Executing Queries, and Retrieving Error Messages
Establishing a connection requires four parameters: hostname (localhost), database username, password, and database name. Checking mysqli_connect_error() immediately detects connection failures. Queries are dispatched via mysqli_query($conn, $sql) or, preferably, via parameterized prepared statements (mysqli_prepare(), mysqli_stmt_bind_param(), mysqli_stmt_execute()) which strictly separate SQL structure from user input and completely neutralize SQL injection. On query failure, mysqli_error($conn) returns the diagnostic message from the MySQL server.
4.3 Inserting and Retrieving Data with PHP
For INSERT, UPDATE, and DELETE queries, mysqli_query() returns a boolean, and mysqli_affected_rows($conn) or mysqli_insert_id($conn) reports the impact. For SELECT queries, mysqli_query() returns a mysqli_result object; rows are iterated via mysqli_fetch_assoc($result) inside a while loop, row counts are read via mysqli_num_rows($result), result memory is freed via mysqli_free_result($result), and connections are closed via mysqli_close($conn).
<?php
$conn = mysqli_connect("localhost", "root", "", "college_db");
if (!$conn) {
die("Database connection failed: " . mysqli_connect_error());
}
mysqli_set_charset($conn, "utf8mb4");
// 1. Prepared INSERT to prevent SQL Injection
$stmt = mysqli_prepare($conn, "INSERT INTO students (full_name, email, dept_id, admission_date, cgpa) VALUES (?, ?, ?, ?, ?)");
$name = "Sneha Menon";
$email = "[email protected]";
$dept = 1;
$date = date("Y-m-d");
$cgpa = 8.95;
mysqli_stmt_bind_param($stmt, "ssisd", $name, $email, $dept, $date, $cgpa);
if (!mysqli_stmt_execute($stmt)) {
echo "Insert error: " . mysqli_error($conn);
} else {
echo "Inserted Student ID: " . mysqli_insert_id($conn) . "\n";
}
mysqli_stmt_close($stmt);
// 2. Retrieving records with mysqli_fetch_assoc()
$result = mysqli_query($conn, "SELECT student_id, full_name, cgpa FROM students ORDER BY cgpa DESC");
if ($result && mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo htmlspecialchars($row['full_name']) . " - CGPA: " . $row['cgpa'] . "<br>";
}
mysqli_free_result($result);
} else {
echo "Query error or empty set: " . mysqli_error($conn);
}
mysqli_close($conn);
?>Chapter 5: Normalization, Indexing, Views, and Transactions in MySQL
5.1 Relational Normalization (1NF, 2NF, 3NF)
Database normalization eliminates redundant data storage and prevents insertion, update, and deletion anomalies by decomposing tables according to functional dependencies:
- First Normal Form (1NF): Every column holds atomic (indivisible) values, there are no repeating groups or comma-separated lists in a single cell, and each row is uniquely identified by a primary key.
- Second Normal Form (2NF): Satisfies 1NF and ensures every non-key attribute is fully functionally dependent on the entire primary key (eliminating partial dependencies in tables with composite keys).
- Third Normal Form (3NF): Satisfies 2NF and eliminates transitive dependencies, ensuring non-key attributes depend strictly on the primary key and not on other non-key attributes (for example, moving department address out of a
studentstable into adepartmentstable).
5.2 Indexes, Views, Subqueries, and UNION
As tables grow to thousands or millions of rows, full table scans degrade application responsiveness. Creating an index (CREATE INDEX idx_student_name ON students(full_name);) builds a balanced B-Tree structure allowing logarithmic-time lookups. Note that PRIMARY KEY and UNIQUE constraints create indexes automatically.
A View (CREATE VIEW v_honor_students AS SELECT ...) stores a named SQL query as a virtual table, simplifying complex multi-table joins and restricting column visibility for reporting users. Subqueries nest a SELECT statement inside another query's WHERE, FROM, or SELECT clause (for example, finding students whose CGPA exceeds the department average). The UNION operator vertically combines result sets from two compatible SELECT queries (removing duplicates, whereas UNION ALL retains all rows).
5.3 ACID Transactions in InnoDB
Operations that span multiple SQL statements—such as transferring fees or enrolling a student while decrementing available course seats—must execute atomically so partial failures never corrupt database state. InnoDB supports explicit transactions via START TRANSACTION, COMMIT (persisting all changes permanently), and ROLLBACK (undoing all changes since transaction start on error).
CREATE INDEX idx_students_cgpa ON students(cgpa);
CREATE OR REPLACE VIEW v_bca_students AS
SELECT s.student_id, s.full_name, s.cgpa, d.dept_name
FROM students s
INNER JOIN departments d ON s.dept_id = d.dept_id
WHERE d.dept_name LIKE '%Computer Applications%';
-- Subquery: Students scoring above overall average CGPA
SELECT full_name, cgpa FROM students
WHERE cgpa > (SELECT AVG(cgpa) FROM students);
-- Atomic transaction example
START TRANSACTION;
UPDATE students SET cgpa = cgpa + 0.10 WHERE student_id = 1;
INSERT INTO departments (dept_name) VALUES ('Data Science');
COMMIT;Chapter 6: Object-Oriented MySQLi and PDO Database Abstraction
6.1 Comparing Procedural MySQLi, OOP MySQLi, and PDO
While procedural MySQLi mirrors classic C-style function calls, modern PHP applications frequently adopt either Object-Oriented MySQLi or PHP Data Objects (PDO) for cleaner exception-based error handling and named parameter binding.
| Feature | Procedural MySQLi | Object-Oriented MySQLi | PDO (PHP Data Objects) |
|---|---|---|---|
| Database Support | MySQL / MariaDB only | MySQL / MariaDB only | 12+ drivers (MySQL, PostgreSQL, SQLite, Oracle) |
| Named Placeholders | No (positional ? only) |
No (positional ? only) |
Yes (:email, :dept_id) and positional ? |
| Error Handling | Manual checks / mysqli_error() |
Exceptions or $conn->error |
Uniform PDOException via ERRMODE_EXCEPTION |
| API Style | Functions (mysqli_query()) |
Methods ($conn->query()) |
Methods ($pdo->prepare(), $stmt->fetchAll()) |
6.2 Complete PDO Connection, Prepared Statements, and Transactions
PDO establishes connections using a Data Source Name (DSN) string specifying the driver, host, database name, and character set (utf8mb4). Enabling PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ensures any SQL failure throws a catchable PDOException, and disabling emulated prepares (PDO::ATTR_EMULATE_PREPARES => false) enforces true native server-side prepared statements.
<?php
$dsn = "mysql:host=localhost;dbname=college_db;charset=utf8mb4";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, "root", "", $options);
// 1. Named placeholder SELECT
$stmt = $pdo->prepare("SELECT student_id, full_name, cgpa FROM students WHERE dept_id = :dept AND cgpa >= :min_cgpa");
$stmt->execute([':dept' => 1, ':min_cgpa' => 8.0]);
$topStudents = $stmt->fetchAll();
foreach ($topStudents as $st) {
echo htmlspecialchars($st['full_name']) . " (" . $st['cgpa'] . ")\n";
}
// 2. Transactional update with automatic rollback on failure
$pdo->beginTransaction();
$upd = $pdo->prepare("UPDATE students SET cgpa = :cgpa WHERE student_id = :id");
$upd->execute([':cgpa' => 9.35, ':id' => 1]);
$pdo->commit();
} catch (PDOException $e) {
if (isset($pdo) && $pdo->inTransaction()) {
$pdo->rollBack();
}
error_log("Database error: " . $e->getMessage());
echo "A database operation failed safely.\n";
}
?>Chapter 7: Stored Routines, Triggers, Backup, and Pagination Queries
7.1 Aggregate Grouping, HAVING, and Pagination Math
Analytical SQL reports frequently group rows by department or category using GROUP BY and filter aggregated groups with HAVING (remembering that WHERE filters individual rows before grouping, whereas HAVING filters summary groups after aggregation). For web pagination displaying L records per page, the SQL OFFSET for 1-based page number p is computed as:
LIMIT).
Worked Numerical Example: To display page p = 4 with L = 15 students per page, Offset = (4 - 1) × 15 = 45, yielding SELECT * FROM students ORDER BY student_id ASC LIMIT 15 OFFSET 45;.
7.2 Stored Procedures, Triggers, and Database Backup
MySQL supports server-side Stored Procedures (CREATE PROCEDURE ... invoked via CALL) to encapsulate multi-step SQL logic inside the database engine, reducing network round-trips. Triggers (CREATE TRIGGER ... BEFORE/AFTER INSERT/UPDATE/DELETE) execute automatically in response to table mutations, ideal for maintaining audit logs or enforcing complex business invariants.
Logical backups and migrations rely on the mysqldump command-line utility (mysqldump -u root -p college_db > backup.sql), which exports table definitions and INSERT statements into a portable SQL script that can be restored via mysql -u root -p college_db < backup.sql.
SELECT d.dept_name, COUNT(s.student_id) AS total_students, ROUND(AVG(s.cgpa), 2) AS avg_cgpa
FROM departments d
LEFT JOIN students s ON d.dept_id = s.dept_id
GROUP BY d.dept_id, d.dept_name
HAVING COUNT(s.student_id) >= 1
ORDER BY avg_cgpa DESC;
DELIMITER //
CREATE PROCEDURE GetDepartmentToppers(IN target_dept INT, IN min_gpa DECIMAL(4,2))
BEGIN
SELECT student_id, full_name, cgpa
FROM students
WHERE dept_id = target_dept AND cgpa >= min_gpa
ORDER BY cgpa DESC;
END //
DELIMITER ;
CALL GetDepartmentToppers(1, 8.50);<?php
$conn = new mysqli("localhost", "root", "", "college_db");
$search = "%" . trim($_GET['q'] ?? '') . "%";
$page = max(1, (int)($_GET['p'] ?? 1));
$limit = 10;
$offset = ($page - 1) * $limit;
$stmt = $conn->prepare(
"SELECT s.student_id, s.full_name, d.dept_name, s.cgpa
FROM students s
INNER JOIN departments d ON s.dept_id = d.dept_id
WHERE s.full_name LIKE ?
ORDER BY s.full_name ASC
LIMIT ? OFFSET ?"
);
$stmt->bind_param("sii", $search, $limit, $offset);
$stmt->execute();
$res = $stmt->get_result();
while ($row = $res->fetch_assoc()) {
echo htmlspecialchars($row['full_name']) . " (" . htmlspecialchars($row['dept_name']) . ") - " . $row['cgpa'] . "\n";
}
$stmt->close();
$conn->close();
?>Chapter 8: MySQL Error Diagnostics, Character Sets, and Security Hardening
8.1 Character Sets, Collations, and UTF-8MB4
Choosing the right character set and collation prevents garbled text and subtle sorting bugs. Legacy MySQL utf8 (alias utf8mb3) only supports 3-byte characters and cannot store modern 4-byte Unicode symbols or emojis. Always configure databases, tables, and PHP connections to use utf8mb4 paired with utf8mb4_unicode_ci (case-insensitive, accent-insensitive sorting) or utf8mb4_general_ci. In PHP, call mysqli_set_charset($conn, "utf8mb4") immediately after connecting.
8.2 Common MySQL Error Codes and Troubleshooting
When executing queries from PHP, mysqli_errno($conn) returns numeric error codes that allow applications to respond gracefully rather than crashing:
| Error Code | SQLSTATE / Name | Root Cause & Resolution |
|---|---|---|
1045 |
Access Denied | Invalid database username or password in connection string; verify MySQL user privileges. |
1049 |
Unknown Database | Target schema does not exist; run CREATE DATABASE or check spelling. |
1062 |
Duplicate Entry | INSERT or UPDATE violated a PRIMARY KEY or UNIQUE constraint (e.g., duplicate email). |
1451 / 1452 |
Foreign Key Constraint | Attempted to delete a parent row referenced by child rows, or insert a child referencing a missing parent ID. |
1064 |
SQL Syntax Error | Malformed SQL keyword, missing comma, or unquoted reserved identifier. |
8.3 Principle of Least Privilege for Database Accounts
Never connect a public-facing PHP web application using the MySQL root account in production. Instead, create a dedicated application user restricted to the target database with only the required DML privileges (SELECT, INSERT, UPDATE, DELETE), omitting administrative DDL privileges such as DROP, ALTER, or GRANT OPTION.
<?php
$conn = new mysqli("localhost", "app_user", "strong_pass", "college_db");
$conn->set_charset("utf8mb4");
$stmt = $conn->prepare("INSERT INTO students (full_name, email, dept_id, admission_date, cgpa) VALUES (?, ?, ?, ?, ?)");
$name = "Kiran Das";
$email = "[email protected]"; // Existing unique email
$dept = 1;
$date = date("Y-m-d");
$cgpa = 8.60;
$stmt->bind_param("ssisd", $name, $email, $dept, $date, $cgpa);
if (!$stmt->execute()) {
if ($conn->errno === 1062) {
echo "Notice: A student with this email address is already registered.\n";
} else {
echo "Database error (" . $conn->errno . "): " . $conn->error . "\n";
}
}
$stmt->close();
$conn->close();
?>8.4 Comprehensive MySQL-PHP Integration Checklist
To ensure reliable database-backed PHP applications, verify four operational practices across every script: (1) centralize connection credentials in a single configuration file included via require_once rather than duplicating hostnames and passwords across pages; (2) always specify utf8mb4 encoding on both MySQL tables and the PHP connection handle so international characters never corrupt; (3) close prepared statements ($stmt->close()), free large result sets (mysqli_free_result()), and close database links (mysqli_close()) promptly to conserve server memory under concurrent load; and (4) log internal database errors privately via error_log() while showing polite, generic messages to end users.
When migrating schemas between development and production environments, maintain versioned SQL migration scripts containing deterministic CREATE TABLE IF NOT EXISTS and ALTER TABLE statements, and verify foreign key constraints and indexes using SHOW CREATE TABLE students; before deploying new PHP code.
Module V: Dynamic Websites, Superglobals, and Lab Integration
Chapter 1: Designing a Website Using HTML and PHP
1.1 Modular Layout Architecture with include and require
Dynamic websites eliminate duplicate HTML boilerplate across pages by factoring shared structural components — such as the document head, navigation bar, sidebar, and footer — into reusable PHP partial files. PHP provides four file-inclusion constructs that differ in failure severity and duplicate-inclusion protection:
| Construct | Missing File Behavior | Duplicate Inclusion Guard | Recommended Use Case |
|---|---|---|---|
include |
Emits E_WARNING; script continues executing. |
No (re-includes every time called). | Optional non-critical UI fragments or banners. |
require |
Emits fatal E_ERROR; halts execution immediately. |
No (re-includes every time called). | Mandatory templates or layout wrappers. |
include_once |
Emits E_WARNING; script continues. |
Yes (tracks included path; skips if already loaded). | Optional helper files that define functions. |
require_once |
Emits fatal E_ERROR; halts execution. |
Yes (guarantees single load per request). | Database configuration, auth guards, and class definitions. |
1.2 Dynamic Routing, CRUD Workflow, and Security Hygiene
A production-grade HTML+PHP website separates configuration (config/db.php), shared layout partials (partials/header.php, partials/footer.php), and feature pages (index.php, create.php, edit.php, delete.php). Three defensive rules govern every dynamic page: escape all database output rendered into HTML with htmlspecialchars() to block XSS, bind all SQL parameters using prepared statements to block SQL injection, and validate CSRF tokens or session authentication before performing state-changing POST operations.
<?php
// --- File: partials/header.php ---
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
$currentPage = basename($_SERVER['PHP_SELF']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?= htmlspecialchars($pageTitle ?? 'Student Portal') ?></title>
</head>
<body>
<nav>
<a href="index.php" class="<?= $currentPage === 'index.php' ? 'active' : '' ?>">Home</a> |
<a href="students.php" class="<?= $currentPage === 'students.php' ? 'active' : '' ?>">Directory</a> |
<a href="logout.php">Logout</a>
</nav>
<hr>
<?php
// --- File: index.php ---
$pageTitle = "Dashboard - BCA Portal";
require_once __DIR__ . '/partials/header.php';
require_once __DIR__ . '/config/db.php';
echo "<h2>Welcome to the Dynamic PHP & MySQL Portal</h2>";
require_once __DIR__ . '/partials/footer.php';
?>Chapter 2: Superglobal Variables and Practical Usage Patterns
2.1 Architectural Roles of All Nine PHP Superglobals
Building interactive websites requires combining PHP's nine superglobal arrays cohesively across authentication, routing, diagnostics, and upload workflows:
$_SERVERfor Routing & Diagnostics: Inspecting$_SERVER['REQUEST_METHOD']differentiates GET page views from POST submissions.$_SERVER['HTTP_USER_AGENT']and$_SERVER['REMOTE_ADDR']support audit logging, while$_SERVER['HTTPS']verifies encrypted transport.$_GETfor Search, Filtering, and Pagination: Query parameters like?dept=1&page=2enable bookmarkable, shareable views. Always cast numeric query parameters with(int)orfilter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT).$_POSTfor Mutating Operations: Login forms, record creation, and deletions must arrive via POST so web crawlers and browser pre-fetching never trigger unintended edits.$_REQUESTCaution: Combines GET, POST, and COOKIE data; avoid in security-sensitive handlers where explicit method separation is required.$_SESSIONand$_COOKIEfor Identity Continuity: On successful login,session_regenerate_id(true)prevents session fixation before storing$_SESSION['auth_user']. Cookies complement sessions by persisting non-sensitive UI preferences such as language or theme.$_FILESand$_ENV:$_FILESpowers profile picture and document submission workflows, while$_ENVkeeps database credentials outside version-controlled source files.$GLOBALSCaution: Although$GLOBALSexposes global state anywhere, modern PHP architecture favors passing dependencies explicitly as function or constructor arguments to keep code testable and predictable.
<?php
session_start();
// Pagination offset calculation using $_GET
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 10;
$offset = ($page - 1) * $perPage;
// Secure authentication check using $_POST and $_SESSION
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['username'], $_POST['password'])) {
$user = trim($_POST['username']);
$pass = $_POST['password'];
$demoHash = password_hash('secret123', PASSWORD_DEFAULT);
if ($user === 'admin' && password_verify($pass, $demoHash)) {
session_regenerate_id(true);
$_SESSION['logged_in'] = true;
$_SESSION['username'] = $user;
$_SESSION['login_ip'] = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
header("Location: dashboard.php");
exit();
} else {
$loginError = "Invalid credentials.";
}
}
?>Chapter 3: Laboratory Environment and Part A Core Experiments
3.1 Setting Up WAMP, XAMPP, and Standalone Apache-MySQL-PHP
Before executing lab experiments, students configure a local server stack. Integrated installers like XAMPP or WAMP bundle Apache, MySQL/MariaDB, PHP, and phpMyAdmin into a single control panel. Alternatively, standalone installation configures Apache's httpd.conf (loading php_module and mapping .php handlers), enables extensions such as extension=mysqli and extension=gd inside php.ini, and starts the mysqld service independently. Source files placed in htdocs/lab/ are accessed in a browser at http://localhost/lab/.
3.2 Part A Lab Programs: Conditionals, Loops, and Strings
Part A establishes core algorithmic fluency in PHP through debugging, branching, iteration, and string analysis:
- Experiment A1 — Simple PHP Programs & Debugging: Displaying server environment details, swapping variables, and calculating simple/compound interest with
error_reporting(E_ALL)enabled. - Experiment A2 — Conditional Statements: Building an electricity tariff calculator or student grade classifier using
if-elseif-elseandswitch. - Experiment A3 — Loop Algorithms: Generating Fibonacci sequences, checking prime numbers, computing factorials, and reversing digits using
for,while, anddo-while. - Experiment A4 — String Handling: Counting vowels/consonants, checking palindromes using
strrev()andstrtolower(), and computing word frequencies.
<?php
function isPalindrome(string $text): bool {
$clean = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $text));
return $clean === strrev($clean);
}
function isPrime(int $n): bool {
if ($n < 2) return false;
for ($i = 2; $i * $i <= $n; $i++) {
if ($n % $i === 0) return false;
}
return true;
}
$sample = "Madam In Eden Im Adam";
echo $sample . " -> " . (isPalindrome($sample) ? "Palindrome" : "Not Palindrome") . "\n";
$primes = [];
for ($k = 1; $k <= 30; $k++) {
if (isPrime($k)) $primes[] = $k;
}
echo "Primes up to 30: " . implode(", ", $primes) . "\n";
?>Chapter 4: Part B Lab Experiments — Arrays, Files, OOP, Forms, and MySQL
4.1 Part B Integrated Practical Workflows
Part B transitions from standalone scripts to multi-file, persistent web applications combining functions, file I/O, OOP, HTML forms, GD images, and MySQL CRUD:
- Experiment B1 — Functions, Arrays & GD Images: Implementing 2D matrix addition using nested loops and generating a dynamic PNG verification badge or bar chart.
- Experiment B2 — File Handling: Reading a CSV student roster with
fgetcsv(), computing class averages, and writing a formatted summary report to disk. - Experiment B3 — OOP Demonstration: Designing a
BankAccountorLibraryItemclass hierarchy demonstrating encapsulation, constructors, and inheritance. - Experiment B4 — Form Processing & Sessions: Creating a multi-step registration form with server-side validation, sticky inputs, and session persistence.
- Experiment B5 — Full PHP-MySQL CRUD Application: Building an end-to-end Student or Inventory Management module supporting Create, Read, Update, and Delete operations against a MySQL database using MySQLi prepared statements.
<?php
$conn = new mysqli("localhost", "root", "", "college_db");
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
// Handle Delete action safely via POST
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) {
$delId = (int) $_POST['delete_id'];
$delStmt = $conn->prepare("DELETE FROM students WHERE student_id = ?");
$delStmt->bind_param("i", $delId);
$delStmt->execute();
$delStmt->close();
}
// Fetch and display records
$rows = $conn->query("SELECT student_id, full_name, email, cgpa FROM students ORDER BY student_id ASC");
while ($r = $rows->fetch_assoc()) {
echo "ID: {$r['student_id']} | " . htmlspecialchars($r['full_name']) . " | CGPA: {$r['cgpa']}\n";
}
$conn->close();
?>Chapter 5: Complete Multi-File Dynamic Website Case Study
5.1 Project Directory Structure and Separation of Concerns
Designing a maintainable HTML and PHP website requires organizing files by responsibility rather than placing all database logic, authentication checks, and HTML markup into a single monolithic script. A clean student portal follows a structured directory layout:
config/db.php: Establishes and returns the shared MySQLi or PDO database connection with UTF-8 encoding.includes/auth.php: Starts the session, checks$_SESSION['user_id'], and redirects unauthenticated visitors tologin.php.partials/header.php&partials/footer.php: Render consistent navigation bars, stylesheets, and page footers across all routes.students_list.php,student_create.php,student_edit.php: Implement Create, Read, Update, and Delete (CRUD) workflows using Post/Redirect/Get (PRG) and prepared statements.
5.2 End-to-End Create and Edit Student Workflows
When an administrator submits student_create.php, the script verifies the CSRF token, validates inputs with trim() and filter_var(), inserts the record using a prepared statement, stores a one-time flash message in $_SESSION['flash'], and redirects to students_list.php. On student_edit.php, an integer id from $_GET['id'] loads the existing row to pre-populate form inputs, and a POST request updates the row safely.
<?php
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/config/db.php';
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$id) {
header("Location: students_list.php");
exit();
}
$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = trim($_POST['full_name'] ?? '');
$email = filter_var(trim($_POST['email'] ?? ''), FILTER_VALIDATE_EMAIL);
$cgpa = filter_var($_POST['cgpa'] ?? '', FILTER_VALIDATE_FLOAT);
if ($name === '' || !$email || $cgpa === false || $cgpa < 0 || $cgpa > 10) {
$errors[] = "Valid name, email, and CGPA (0-10) are required.";
} else {
$stmt = $conn->prepare("UPDATE students SET full_name = ?, email = ?, cgpa = ? WHERE student_id = ?");
$stmt->bind_param("ssdi", $name, $email, $cgpa, $id);
$stmt->execute();
$stmt->close();
$_SESSION['flash'] = "Student record updated successfully.";
header("Location: students_list.php");
exit();
}
}
$sel = $conn->prepare("SELECT full_name, email, cgpa FROM students WHERE student_id = ?");
$sel->bind_param("i", $id);
$sel->execute();
$student = $sel->get_result()->fetch_assoc();
$sel->close();
if (!$student) {
die("Record not found.");
}
require_once __DIR__ . '/partials/header.php';
?>
<h2>Edit Student Record</h2>
<form method="POST" action="student_edit.php?id=<?= $id ?>">
<label>Full Name: <input type="text" name="full_name" value="<?= htmlspecialchars($student['full_name']) ?>"></label><br>
<label>Email: <input type="email" name="email" value="<?= htmlspecialchars($student['email']) ?>"></label><br>
<label>CGPA: <input type="number" step="0.01" name="cgpa" value="<?= htmlspecialchars((string)$student['cgpa']) ?>"></label><br>
<button type="submit">Save Changes</button>
</form>
<?php require_once __DIR__ . '/partials/footer.php'; ?>Chapter 6: Laboratory Manual Walkthroughs (Part A & Part B)
6.1 Part A Walkthrough: Electricity Tariff and Fibonacci Generator
Part A lab exercises strengthen algorithmic reasoning in PHP. In the Electricity Tariff experiment, tiered slab rates are evaluated using if-elseif-else blocks. For example, if the first 100 units cost Rs. 3.00/unit, the next 100 units cost Rs. 4.50/unit, and units above 200 cost Rs. 6.00/unit, total bill B for 250 units is computed cleanly by decomposing slabs: 100 × 3.00 + 100 × 4.50 + 50 × 6.00 = 300 + 450 + 300 = Rs. 1,050.00.
6.2 Part B Walkthrough: OOP Bank Account and File Persistence
Part B lab exercises integrate OOP encapsulation with form/database workflows. A BankAccount class protects its $balance property as private, validating deposits and withdrawals inside public methods to prevent negative balances. Similarly, a 2D Matrix Addition lab program validates matching dimensions before summing corresponding elements $C[$i][$j] = $A[$i][$j] + $B[$i][$j].
<?php
class BankAccount {
private float $balance;
public function __construct(private string $holder, float $openingBalance = 0.0) {
$this->balance = max(0.0, $openingBalance);
}
public function deposit(float $amount): void {
if ($amount > 0) $this->balance += $amount;
}
public function withdraw(float $amount): bool {
if ($amount > 0 && $amount <= $this->balance) {
$this->balance -= $amount;
return true;
}
return false;
}
public function getSummary(): string {
return "{$this->holder} | Balance: Rs. " . number_format($this->balance, 2);
}
}
function addMatrices(array $A, array $B): array {
$rows = count($A);
$cols = count($A[0]);
$C = [];
for ($i = 0; $i < $rows; $i++) {
for ($j = 0; $j < $cols; $j++) {
$C[$i][$j] = $A[$i][$j] + $B[$i][$j];
}
}
return $C;
}
$acc = new BankAccount("Arjun K", 5000);
$acc->deposit(1500);
$acc->withdraw(2000);
echo $acc->getSummary() . "\n";
?>Chapter 7: Deployment Checklist, Debugging, and Performance Tuning
7.1 Configuring php.ini for Development vs. Production
Deploying a PHP and MySQL website from a local XAMPP/WAMP environment to a live server requires adjusting critical php.ini directives to balance diagnostics during development against strict hardening in production:
| Directive | Development Value | Production Value | Operational Reason |
|---|---|---|---|
display_errors |
On |
Off |
Prevents leaking stack traces, file paths, or SQL details to visitors. |
log_errors |
On |
On |
Records all warnings and exceptions into a protected server log file. |
error_reporting |
E_ALL |
E_ALL & ~E_DEPRECATED |
Surfaces every potential bug during testing while keeping logs clean. |
opcache.enable |
1 (short revalidate) |
1 (tuned memory) |
Caches compiled Zend opcodes in shared RAM, boosting throughput significantly. |
session.cookie_httponly |
1 |
1 |
Blocks JavaScript access to PHPSESSID cookies against XSS theft. |
7.2 Structured Debugging and SQL Query Profiling
Effective PHP debugging combines built-in inspection tools with systematic isolation. For variable inspection during development, wrapping var_dump($data) inside <pre> tags reveals exact data types, string byte lengths, and nested array keys. For MySQL bottlenecks, prefixing slow SELECT statements with EXPLAIN verifies whether the optimizer utilizes B-Tree indexes or falls back to full table scans.
7.3 Security Audit Checklist for PHP-MySQL Websites
Before releasing any dynamic PHP+MySQL application, verify five non-negotiable security invariants across all endpoints: (1) all passwords are hashed with password_hash($pwd, PASSWORD_DEFAULT) and verified with password_verify()—never MD5 or SHA-1; (2) all SQL queries use prepared statements with bound parameters; (3) all HTML output derived from user input or database fields is escaped with htmlspecialchars(); (4) all state-changing POST forms validate a session-bound CSRF token; and (5) file uploads validate extension, byte size, and true MIME type before moving outside executable script paths.
<?php
require_once __DIR__ . '/config/db.php';
function registerUser(mysqli $conn, string $username, string $plainPassword): bool {
$cleanUser = trim($username);
if (strlen($cleanUser) < 3 || strlen($plainPassword) < 8) {
return false;
}
$hash = password_hash($plainPassword, PASSWORD_DEFAULT);
$stmt = $conn->prepare("INSERT INTO users (username, password_hash) VALUES (?, ?)");
$stmt->bind_param("ss", $cleanUser, $hash);
$ok = $stmt->execute();
$stmt->close();
return $ok;
}
function verifyLogin(mysqli $conn, string $username, string $plainPassword): ?array {
$stmt = $conn->prepare("SELECT user_id, username, password_hash FROM users WHERE username = ? LIMIT 1");
$stmt->bind_param("s", $username);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
$stmt->close();
if ($row && password_verify($plainPassword, $row['password_hash'])) {
return ['user_id' => $row['user_id'], 'username' => $row['username']];
}
return null;
}
?>Chapter 8: RESTful JSON Endpoints and AJAX Integration with PHP & MySQL
8.1 Serving JSON APIs from PHP
Modern HTML and PHP websites frequently combine server-rendered views with asynchronous JavaScript (fetch()) calls for live search, dynamic dropdown filtering, or inline status updates without reloading the entire page. A PHP endpoint serving JSON sets the Content-Type: application/json; charset=utf-8 header, queries MySQL via prepared statements, and outputs json_encode($response).
8.2 Consuming a PHP-MySQL Endpoint from HTML/JavaScript
On the frontend, JavaScript sends a request to api_students.php?q=aditi, parses the JSON response, and updates the DOM safely using textContent (avoiding unsafe innerHTML injection). Combining server-side prepared statements with client-side safe DOM updates delivers responsive, secure user interfaces.
<?php
header("Content-Type: application/json; charset=utf-8");
require_once __DIR__ . '/config/db.php';
$query = trim($_GET['q'] ?? '');
$like = "%" . $query . "%";
$stmt = $conn->prepare(
"SELECT student_id, full_name, cgpa
FROM students
WHERE full_name LIKE ?
ORDER BY full_name ASC
LIMIT 20"
);
$stmt->bind_param("s", $like);
$stmt->execute();
$result = $stmt->get_result();
$items = [];
while ($row = $result->fetch_assoc()) {
$items[] = [
'id' => (int) $row['student_id'],
'name' => $row['full_name'],
'cgpa' => (float) $row['cgpa']
];
}
$stmt->close();
$conn->close();
echo json_encode(['status' => 'ok', 'count' => count($items), 'data' => $items]);
?>8.3 Lab Record Documentation and Viva Preparation Guidelines
When documenting the 15–20 PHP and MySQL laboratory experiments required under Part A and Part B, structure each experiment entry clearly with four elements: the problem statement, the database schema (for Part B MySQL tasks), the complete modular PHP/HTML source listing, and sample input/output traces verified in a local Apache/MySQL environment. Always test edge cases—such as empty form submissions, invalid email formats, duplicate primary keys, division by zero, and missing files—to confirm that your error-handling branches operate cleanly without exposing raw PHP warnings.
During practical demonstrations, be prepared to explain the difference between client-side HTML validation and server-side PHP validation, trace how HTTP GET and POST payloads populate $_GET and $_POST, demonstrate how session_start() and cookies preserve state across stateless HTTP requests, and justify why prepared statements neutralize SQL injection compared to string concatenation.
8.4 Superglobals and Lab Experiment Mapping Matrix
The matrix below maps core laboratory tasks in Part A and Part B to the primary PHP superglobals and MySQL/GD subsystems exercised during execution:
| Lab Task Area | Primary PHP Constructs | Key Superglobals & Extensions |
|---|---|---|
| Part A: Conditionals, Loops & Strings | if-elseif, switch, for, while, strrev() |
CLI / $_GET for test inputs |
| Part B: Functions, Arrays & GD Images | Multidimensional arrays, imagecreatetruecolor(), imagepng() |
extension=gd, header("Content-Type") |
| Part B: File I/O & OOP | fopen(), fgetcsv(), classes, inheritance, interfaces |
Filesystem streams, SPL interfaces |
| Part B: Forms & PHP-MySQL CRUD | Sticky forms, PRG redirects, prepared statements | $_POST, $_GET, $_SESSION, $_FILES, mysqli |
University of Kerala FYUGP Academic Framework
Syllabus details for BCA Semester 5 under official University of Kerala regulations.
Assessment comprises a 70-mark End-Semester Examination (2.5 Hours) and 30-mark Continuous Internal Evaluation.
About PHP and MySQL (University of Kerala BCA Sem 5)
PHP and MySQL (UK5DSCCAP300 • 4 Credits • 60 Hours (4 Hrs/Week)) is a DSC offering under the Bachelor of Computer Applications (BCA) Four-Year Undergraduate Programme (UoK FYUGP Regulations 2024 / 2025) at the University of Kerala. Structured across five sequentially integrated instructional modules, the course builds solid theoretical foundations and hands-on technical proficiency in php and mysql. Students engage with core computing principles, structured problem-solving, implementation techniques, and modern industry practices aligned with Kerala State Higher Education Council outcome-based education standards.
PHP and MySQL Module-by-Module Curriculum Breakdown
Official syllabus unit modules prescribed by the University of Kerala FYUGP framework:
Introduction to PHP
PHP, originally created as Personal Home Page Tools and now maintained as the recursive acronym PHP: Hypertext Preprocessor, is a widely deployed open-source, general-purpose server-side scripting language engineered specifically for dynamic web development. Unlike client-side languages such as JavaScript that execute inside the user's web browser, PHP executes on the web server before any Hypertext Markup Language (HTML) payload is transmitted over Hypertext Transfer Protocol (HTTP) to the client.
Arrays and OOP
In PHP, an array is not a fixed-size contiguous C block; rather, it is an ordered hash map that associates keys (integers or strings) with values of any type. This unified data structure seamlessly supports lists, dictionaries, stacks, queues, and nested trees. Every element maintains insertion order unless explicitly sorted or re-indexed. The foreach loop is the canonical mechanism for iterating over both indexed and associative arrays without relying on contiguous integer keys.
Forms, State Management, and Images
HTML forms collect structured input from users and transmit it to a server-side PHP script specified by the action attribute using the HTTP method declared in method. Choosing between GET and POST affects visibility, payload capacity, bookmarking, and idempotency. When a form presents multiple checkboxes, multi-select dropdowns, or dynamic rows sharing the same logical field, appending empty square brackets to the HTML name attribute (for example, name="skills[]" ) instructs PHP to automatically assemble all checked values into an indexed array inside $_POST['skills'].
MySQL and PHP-MySQL Integration
MySQL is the world's most widely adopted open-source Relational Database Management System (RDBMS), organizing data into structured tables composed of rows (tuples) and columns (attributes) linked by keys. Operating in a client-server architecture, the MySQL daemon ( mysqld ) manages concurrent connections, query parsing, optimization, and durable disk storage. Selecting exact column data types minimizes storage footprint, accelerates index lookups, and enforces domain integrity at the database layer.
Dynamic Websites, Superglobals, and Lab Integration
Dynamic websites eliminate duplicate HTML boilerplate across pages by factoring shared structural components — such as the document head, navigation bar, sidebar, and footer — into reusable PHP partial files. PHP provides four file-inclusion constructs that differ in failure severity and duplicate-inclusion protection: A production-grade HTML+PHP website separates configuration ( config/db.php ), shared layout partials ( partials/header.
Core Curriculum & Key Topics
- Overview of PHP and Server-Side Architecture
- 1 Evolution and Role of PHP in Web Engineering
- 2 Request-Response Lifecycle in a PHP Environment
- 3 Benefits and Drawbacks of PHP as a Server-Side Script
- 4 Embedding PHP in HTML and Development Stack Setup
- PHP Language Basics, Variables, and Superglobals
- 1 Lexical Rules, Comments, and Output Statements
- 2 Variables, Naming Rules, and Constants
Learning Outcomes
- Demonstrate authoritative comprehension of the foundational concepts, architectures, and principles of php and mysql.
- Apply algorithmic, programming, or analytical techniques to design and evaluate practical computing solutions.
- Analyze system trade-offs, security considerations, and industry standards relevant to modern software and IT environments.
- Implement, test, and document structured technical workflows aligned with professional computing practices.
- Achieve exam-ready mastery of University of Kerala FYUGP BCA question patterns across short concepts, technical comparisons, and comprehensive essays.
University of Kerala Examination Scheme for PHP and MySQL
The evaluation framework for PHP and MySQL (UK5DSCCAP300) under University of Kerala FYUGP regulations combines Continuous Internal Evaluation (30 Marks) with the university End-Semester Examination (70 Marks) for a total of 100 Marks (2.5 Hours duration):
10 Questions × 3 Marks (Maximum ceiling 24 Marks). Short definitional and conceptual questions covering all 5 syllabus modules.
8 Questions × 6 Marks (Maximum ceiling 36 Marks). Paragraph questions, comparative evaluations, and analytical problems.
2 Questions × 10 Marks (Answer any 1 for 10 Marks). Long-form essay or comprehensive numerical workout problem.
Exam Preparation Strategy:
To score top marks in the University of Kerala UK5DSCCAP300 (PHP and MySQL) examination: 1. Write Clean, Traceable Code Snippets: Always include well-indented syntax examples with sample input and expected output for programming questions. 2. Explain Logic & Control Flow Step-by-Step: Before writing full programs, briefly outline the algorithm, key functions, or class hierarchy so examiners can award full step marks. 3. Highlight Edge Cases & Syntax Rules: Mention common runtime pitfalls, data type constraints, or security/validation practices where relevant. 4. Manage Time Across Sections: For the 2.5-hour 70-mark external paper, allocate 25 minutes to Part A definitions, 50 minutes to Part B short programs and comparisons, and 75 minutes to Part C full code-backed essays.
Exam Preparation & Study Guides — PHP and MySQL
What is Overview of PHP and why is it important in PHP and MySQL?
PHP (Hypertext Preprocessor) is an open-source, server-side scripting language executed by the Zend Engine on a web server to produce dynamic HTML, JSON, or XML responses before transmission over HTTP.
What are the core elements of Operators, Expressions, and Flow Control Functions in PHP and MySQL?
Expressions combine operands and operators according to precedence and associativity rules, directing execution via conditional and iterative constructs.
What are the core elements of Date and Time Functions in PHP and MySQL?
PHP handles temporal data through Unix timestamps (seconds since Jan 1, 1970 UTC) and object-oriented
What is Hidden Fields, Redirects, and Sending Mail and why is it important in PHP and MySQL?
State tokens, safe redirects, and email dispatch complete standard form workflows.
What are the core elements of MySQL Data Types in PHP and MySQL?
Choosing accurate column types optimizes storage and enforces domain constraints.
What is the official course code and credit structure for PHP and MySQL at University of Kerala?
PHP and MySQL carries the official course code UK5DSCCAP300 under the University of Kerala FYUGP BCA framework. It is awarded 4 credits (60 Hours (4 Hrs/Week)), evaluated through 30 marks Continuous Internal Evaluation (CIE) and 70 marks End-Semester Examination (ESE).
Where can students download free PDF notes for PHP and MySQL?
Students can read all 5 module notes online and download verified chapter-wise PDFs, combined exam notes, and quick revision sheets for PHP and MySQL (UK5DSCCAP300) directly from DegreeLive (degreelive.in) with zero paywalls or sign-ups.
Course outlines and study notes follow official University of Kerala curricula. Curated by Anoop (Thiruvananthapuram).
For feedback or corrections, contact [email protected].
Related Study Resources & Student Support
Related Semester 5 Subjects
Browse study notes for other courses in BCA Sem 5:
Financial Aid & Grants 2026-27
Check eligibility criteria and deadlines for Kerala government and merit scholarships (e-Grantz 3.0, KSHEC, DCE).
Request Notes
Can't find what you're looking for? Let us know which subject notes you need.