Comprehensive Guide to PHP and MySQL Fundamentals
Section I: Basic Building Blocks, Flow Control, and Functions in PHP
Basic Building Blocks of PHP
- PHP Tags: PHP scripts are executed on the server and enclosed within delimiter tags that tell the server parser where the code starts and finishes:
- Standard canonical tags:
<?php ... ?> - Short echo tags:
<?= $expression ?>(evaluates and prints the expression directly)
- Standard canonical tags:
- Variables: Used to store data in memory during runtime:
- Must begin with a dollar sign (
$), followed by an underscore or letter, and cannot begin with a number. - Variables are dynamically typed, meaning the interpreter assigns the data type automatically based on the assigned value.
- Variable names are case-sensitive (e.g.,
VARare distinct).
- Must begin with a dollar sign (
- Data Types: PHP supports eight primitive data types categorized into three groups:
- Scalar types: Integer (whole numbers), Float/Double (floating-point numbers), String (sequences of characters), and Boolean (
trueorfalse). - Compound types: Array (ordered maps) and Object (instances of classes).
- Special types:
NULL(a variable without a value) and Resource (special variables holding references to external resources, such as database connections or file handles).
- Scalar types: Integer (whole numbers), Float/Double (floating-point numbers), String (sequences of characters), and Boolean (
- Constants: Identifiers for simple values that cannot be modified or undefined during script execution:
- Defined using the
define()function:define("SITE_NAME", "StudyPortal"); - Defined using the
constkeyword at compile-time:const MAX_UPLOAD = 100; - By convention, constants are written in uppercase and do not use a leading dollar sign (
$).
- Defined using the
- Operators: Mathematical and logical constructs used to perform operations on variables and values:
- Arithmetic:
+,-,*,/,%(modulo),**(exponentiation). - Assignment:
=,+=,-=,*=,/=,.=(concatenation assignment). - Comparison:
==(loose equality),===(strict equality: identical value and type),!=,<>,!==(strict inequality),<,>,<=,>=,<=>(spaceship operator). - Logical:
&&(and),||(or),!(not),and,or,xor. - String Operator:
.(dot operator for concatenation).
- Arithmetic:
- Literals and Expressions: An expression is any valid combination of variables, literals, and operators that evaluates to a specific value. Every PHP statement typically terminates with a semicolon (
;).
- PHP Tags: PHP scripts are executed on the server and enclosed within delimiter tags that tell the server parser where the code starts and finishes:
Flow Control Statements in PHP
- Conditional Statements: Direct program execution based on boolean conditions:
ifstatement: Executes a block of code if a specified condition evaluates totrue.if...elsestatement: Executes the first block if the condition istrue; executes the alternativeelseblock iffalse.if...elseif...elseconstruct: Evaluates multiple conditions sequentially until one evaluates totrue.switchstatement: Compares an expression to multiplecasevalues to prevent deeply nestedifstatements. Each case executes until abreakstatement is reached; an optionaldefaultcase handles unmatched conditions.
- Looping Statements (Iteration): Execute a block of code repeatedly while a condition remains
true:whileloop: Checks the test condition before executing the loop body. If the condition is false initially, the body does not execute.do...whileloop: Evaluates the test condition after executing the loop body, guaranteeing at least one execution.forloop: Standard counter-controlled loop with three expressions: initialization, condition evaluation, and increment/decrement step.foreachloop: Iterates specifically over arrays or traversable objects. Extracts elements asforeach ($array as $value)or key-value pairs asforeach ($array as $key => $value).
- Jump and Execution Control Statements:
break: Immediately terminates execution of the nearest enclosingfor,foreach,while,do...while, orswitchstructure.continue: Skips the remainder of the current loop iteration and advances to the evaluation of the next cycle's condition.return: Immediately terminates execution of a function and returns control (and an optional value) to the caller.
- Conditional Statements: Direct program execution based on boolean conditions:
Different Types of Functions in PHP
- Built-in / Core Functions: Pre-defined functions provided by the PHP engine for core operations, such as mathematical calculations (
abs(),round()), time handling (date(),time()), and type validation (is_numeric(),isset()). - User-Defined Functions: Custom blocks of code defined by the developer using the
functionkeyword to perform modular, reusable logic:- Can accept optional or mandatory positional arguments.
- Can support default parameter values and type hinting (e.g.,
int $x,string $y). - Can return single values or data structures via the
returnstatement.
- Variable Functions: PHP allows variable names to act dynamically as function names. If a variable evaluates to a string matching an existing function name followed by parentheses, PHP will invoke that function.
- Anonymous Functions (Closures): Functions defined without a specified name, typically assigned to variables or passed as callback arguments into other functions (e.g., within
array_map()):- Can inherit variables from the parent scope using the
uselanguage construct.
- Can inherit variables from the parent scope using the
- Arrow Functions: Introduced in modern PHP (PHP 7.4+) as a more concise syntax for simple one-line anonymous functions using the
fnkeyword, with automatic capture of outer-scope variables by value. - Recursive Functions: Functions that invoke themselves directly or indirectly to solve problems that can be partitioned into self-similar sub-problems (e.g., calculating factorials or traversing hierarchical tree structures).
- Built-in / Core Functions: Pre-defined functions provided by the PHP engine for core operations, such as mathematical calculations (
Section II: Arrays, String Manipulation, and Object-Oriented Programming
Arrays in PHP
- Definition: An array in PHP is an ordered map that associates values to keys. Unlike static arrays in low-level languages, PHP arrays are dynamically sized, can grow or shrink at runtime, and can hold mixed data types simultaneously.
- Array Creation: Arrays are instantiated using two primary syntaxes:
- Using the
array()construct:$items = array("apple", "banana", "cherry"); - Using the short array syntax
[]:$items = ["apple", "banana", "cherry"];
- Using the
- Array Classifications:
- Indexed Arrays: Elements are referenced by a zero-based numeric index (
0, 1, 2, \text{...}). New items can be appended automatically using$arr[] = $new_val;. - Associative Arrays: Elements are referenced by descriptive named keys (strings). Defined using the double arrow operator:
$user = ["name" => "Alice", "role" => "Admin"];. - Multidimensional Arrays: Arrays containing one or more nested arrays as elements, used to represent matrices, grids, or tabular records.
- Indexed Arrays: Elements are referenced by a zero-based numeric index (
String Manipulating Functions in PHP
- Length and Inspection Functions:
strlen($str): Returns the total byte length of a string.str_word_count($str): Counts the number of words present within a string.
- Search and Position Functions:
strpos($haystack, $needle): Finds the numeric position of the first occurrence of a substring (returnsfalseif not found).strrpos($haystack, $needle): Finds the position of the last occurrence of a substring.
- Case Alteration Functions:
strtolower($str): Converts all alphabetic characters in a string to lowercase.strtoupper($str): Converts all alphabetic characters in a string to uppercase.ucfirst($str): Capitalizes the very first character of the string.ucwords($str): Capitalizes the first character of each word throughout the string.
- Substrings and Replacement Functions:
substr($str, $start, $length): Extracts and returns a specified segment of a string starting from an offset index.str_replace($search, $replace, $subject): Replaces all occurrences of a search string with a replacement string inside a target string.
- Sanitization and Trimming Functions:
trim($str): Strips whitespace (or other specified characters) from both the beginning and end of a string.ltrim(str): Strips whitespace from the left or right side only.
- Conversion and Splitting Functions:
explode($delimiter, $string): Splits a string into an indexed array of substrings using a designated delimiter.implode($glue, $array)(orjoin()): Joins array elements into a single contiguous string separated by the glue string.
- Length and Inspection Functions:
Accessing Objects in PHP
- Object-Oriented Programming (OOP) Fundamentals:
- Class: The blueprint or template defining the properties (variables) and methods (functions) that an entity possesses.
- Object: An individual instance of a class allocated in memory.
- Object Instantiation: Created using the
newkeyword, which triggers the class constructor method__construct():- Example:
$account = new BankAccount();
- Example:
- Object Operator (
->): The primary operator used to interact with non-static members of an instantiated object:- Accessing Properties: Read or write instance variables via
on the property name). - Calling Methods: Invoke member functions via
arguments);.
- Accessing Properties: Read or write instance variables via
- The Scope Resolution Operator (
::):- Used to access static properties, static methods, and class constants directly without requiring object instantiation:
ClassName::STATIC_CONSTANT;ClassName::$staticProperty;ClassName::staticMethod();
- Internal Self-Reference (
this->propertyName).
- Object-Oriented Programming (OOP) Fundamentals:
Section III: HTML Integration, Form Handling with Arrays, and Exception Handling
Combining HTML and PHP Code
- Interspersed Execution: PHP files (
.php) are parsed on the web server from top to bottom. Any content located outside of<?php ... ?>tags is treated as raw output and sent directly to the client browser without evaluation. - Standard Embedding Method: Embedding processing logic or variable output inside HTML markup:
- HTML elements wrap PHP blocks to render dynamic content into attributes or tag bodies.
- Alternative Syntax for Control Structures: When mixing control structures with dense HTML, PHP provides an alternative syntax to improve template readability:
- Replaces curly braces
{with a colon:and closing braces}with dedicated keywords such asendif;,endfor;,endforeach;, andendwhile;.
- Replaces curly braces
- Short Echo Tag Integration: Simplifies echoing values inside HTML elements:
<h1><?= $pageTitle ?></h1>replaces<h1><?php echo $pageTitle; ?></h1>.
- Interspersed Execution: PHP files (
Creating Forms and Processing Form Input with User-Defined Arrays
- HTML Form Setup: HTML
<form>elements send user input to a server endpoint via theGETorPOSTHTTP methods:action: Specifies the destination script URL.method: Defines whether data is passed in the URL query string (GET) or the request body (POST).
- Array Syntax in Form Inputs:
- HTML input elements (such as checkboxes, multi-select elements, or dynamic line items) can submit groups of data by appending empty brackets
[]or named keys[key]to thenameattribute. - Example for multiple selections:
<input type="checkbox" name="skills[]" value="PHP"><input type="checkbox" name="skills[]" value="MySQL">
- Example for associative/grouped array inputs:
<input type="text" name="user[firstname]"><input type="text" name="user[lastname]">
- HTML input elements (such as checkboxes, multi-select elements, or dynamic line items) can submit groups of data by appending empty brackets
- Processing Form Arrays in PHP:
- When submitted, PHP automatically parses input names containing
[]and constructs a multi-level array inside the superglobal arrays (_GET). - Accessing values: If multiple skills are checked,
$_POST['skills']is received as an indexed array containing["PHP", "MySQL"]. - Data can be validated using
isset()orempty()and traversed iteratively usingforeach ($_POST['skills'] as $skill).
- When submitted, PHP automatically parses input names containing
- HTML Form Setup: HTML
Exception Handling in PHP
- Core Concepts: Exception handling is an object-oriented approach for gracefully handling runtime errors and exceptional events rather than halting script execution prematurely.
- Structure of Exception Handling Blocks:
tryblock: Encapsulates code that may potentially throw an exception during execution.throwstatement: Explicitly triggers an exception, generating an instance of theExceptionclass (or a subclass):throw new Exception("Invalid input detected");.catchblock: Intercepts and handles the thrown exception object. Multiplecatchblocks can be chained to handle different exception classes individually.finallyblock: An optional block placed aftercatchblocks that always executes, regardless of whether an exception was thrown or caught (often used for cleanup, such as closing file handles or releasing connections).
- Methods of the Built-in
ExceptionClass:$e->getMessage(): Retrieves the error message string passed when the exception was thrown.$e->getCode(): Retrieves the numeric exception code.$e->getFile(): Returns the full filesystem path to the script file where the exception occurred.$e->getLine(): Returns the exact line number where the exception was thrown.$e->getTraceAsString(): Formats and outputs the complete stack execution trace as a formatted string.
- Global Exception Handlers: Developers can define fallback handlers using
set_exception_handler('myHandlerFunction')to catch any uncaught exceptions globally before script termination.
Section IV: State Management — Cookies and Sessions
Cookies in PHP
- Definition: A cookie is a small text file (typically capped at ) created by the server and stored on the client machine's browser. It allows web servers to track user identity, remember preferences, and retain state across independent HTTP requests.
- Setting Cookies with
setcookie():- Cookies must be transmitted within HTTP response headers. Consequently,
setcookie()must be called before any raw output (HTML, whitespace, or echo statements) is sent to the browser. - Syntax signature:
setcookie($name, $value, $expire, $path, $domain, $secure, $httponly);
- Cookies must be transmitted within HTTP response headers. Consequently,
- Parameter Breakdown:
name: The identifier used to reference the cookie.value: The data payload stored within the cookie (stored as a string).expire: Unix timestamp indicating when the cookie becomes invalid (e.g.,time() + (86400 * 30)sets expiration for 30 days into the future). If set to0or omitted, it acts as a session cookie that expires when the browser closes.path: The server path across which the cookie is available (defaulting to/for the entire domain).domain: The domain or subdomain that can access the cookie.secure: A boolean value; if set totrue, the cookie is only transmitted over encrypted HTTPS connections.httponly: A boolean value; if set totrue, the cookie cannot be accessed by client-side scripts (such as JavaScriptdocument.cookie), mitigating Cross-Site Scripting (XSS) attacks.
- Retrieving Cookie Values: When the browser issues subsequent requests, cookie data is submitted in the HTTP header and parsed into the superglobal array
$_COOKIE['cookie_name'].
Sessions in PHP
- Definition: A session provides server-side storage for user-specific data across multiple pages. Unlike cookies, sensitive session data resides entirely on the web server, making it more secure.
- Architecture of Sessions:
- The server generates a unique, pseudo-random identifier known as a Session ID (SID).
- The SID is sent to the client browser, typically stored in a temporary client cookie named
PHPSESSID. - On subsequent requests, the browser sends the
PHPSESSIDcookie, allowing the server to retrieve and load the corresponding session file from its storage directory.
- Starting a Session:
- Invoked using
session_start();at the beginning of each page that requires session state. - Like
setcookie(),session_start()modifies HTTP response headers and must be executed before sending any output to the browser. - Once initialized, data is read and written using the superglobal associative array
_SESSION['user_id'] = 42;).
- Invoked using
Destroying Sessions and Unsetting Variables
- Unsetting Session Variables:
unset($_SESSION['key']): Removes a specific variable from the active session.session_unset(): Frees and clears all registered variables currently residing in the$_SESSIONsuperglobal array, leaving it empty.$_SESSION = array();: Directly overwrites the superglobal with an empty array to reset all active session variables in memory.
- Destroying the Entire Session:
session_destroy(): Completely invalidates the server-side session storage file. It frees the storage allocated to the current session ID on disk.- Crucial Detail: Calling
session_destroy()does not immediately unset the values stored in the in-memory$_SESSIONsuperglobal for the remainder of the active script execution, nor does it delete thePHPSESSIDcookie from the client browser.
- Comprehensive Procedure for Full Session Destruction:
- Step 1: Initialize session via
session_start();. - Step 2: Clear all values in memory:
$_SESSION = [];. - Step 3: Expire the client-side session cookie: Check
ini_get("session.use_cookies"), and if true, executesetcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);using parameters fetched viasession_get_cookie_params(). - Step 4: Erase the physical server-side session record via
session_destroy();.
- Step 1: Initialize session via
- Unsetting Session Variables:
Section V: Database Connectivity — MySQL vs. MySQLi
Overview of Database Extensions in PHP
- Interaction between PHP and the relational database management system MySQL has evolved over time.
- The legacy, original driver is referred to as MySQL (functions prefixed with
mysql_*). - The modern, improved driver is known as MySQLi (where the "i" stands for Improved, functions/methods prefixed with
mysqli_*).
Detailed Differences Between MySQL and MySQLi
Architectural Programming Paradigms:
- MySQL: Strictly procedural. Every operation requires passing resource pointers through individual function calls (e.g.,
mysql_connect(),mysql_query()). - MySQLi: Dual interface. Supports both procedural execution (
mysqli_connect()) and an Object-Oriented Programming (OOP) model ($mysqli = new mysqli(); $mysqli->query();).
- MySQL: Strictly procedural. Every operation requires passing resource pointers through individual function calls (e.g.,
Prepared Statements and Parameter Binding:
- MySQL: Does not support server-side prepared statements. Query parameters must be concatenated manually into SQL strings, requiring manual sanitization functions like
mysql_real_escape_string(). - MySQLi: Fully supports prepared statements and parameter binding (
$stmt = $mysqli->prepare(...),$stmt->bind_param(...)). SQL statements and data inputs are parsed separately, mitigating SQL injection vulnerabilities.
- MySQL: Does not support server-side prepared statements. Query parameters must be concatenated manually into SQL strings, requiring manual sanitization functions like
Security Profile:
- MySQL: High risk of SQL injection vulnerabilities due to reliance on manual string escaping.
- MySQLi: High security profile via parameterized queries that prevent user data from being interpreted as executable SQL instructions.
Support for Multiple Statements:
- MySQL: Unable to execute multiple SQL queries in a single string call.
- MySQLi: Provides
mysqli_multi_query(), allowing multiple SQL statements separated by semicolons to execute within a single transaction round-trip.
Transaction Management:
- MySQL: Lacks dedicated built-in transactional API methods; requires executing manual SQL commands (
BEGIN WORK,COMMIT,ROLLBACK) via standard query functions. - MySQLi: Provides native programmatic support for transaction control using methods such as
mysqli->commit(), and$mysqli->rollback().
- MySQL: Lacks dedicated built-in transactional API methods; requires executing manual SQL commands (
PHP Version Support and Deprecation Status:
- MySQL: Deprecated in PHP 5.5.0 (emits
E_DEPRECATEDwarnings) and officially removed in PHP 7.0.0. Scripts relying onmysql_*functions cannot run on modern PHP versions. - MySQLi: Actively maintained, supported, and included by default across PHP 5, PHP 7, and PHP 8 releases.
- MySQL: Deprecated in PHP 5.5.0 (emits