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)
    • 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., var</code>and<code>var</code> and <code>VAR are distinct).
    • 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 (true or false).
      • 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).
    • 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 const keyword at compile-time: const MAX_UPLOAD = 100;
      • By convention, constants are written in uppercase and do not use a leading dollar sign ($).
    • 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).
    • 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 (;).
  • Flow Control Statements in PHP

    • Conditional Statements: Direct program execution based on boolean conditions:
      • if statement: Executes a block of code if a specified condition evaluates to true.
      • if...else statement: Executes the first block if the condition is true; executes the alternative else block if false.
      • if...elseif...else construct: Evaluates multiple conditions sequentially until one evaluates to true.
      • switch statement: Compares an expression to multiple case values to prevent deeply nested if statements. Each case executes until a break statement is reached; an optional default case handles unmatched conditions.
    • Looping Statements (Iteration): Execute a block of code repeatedly while a condition remains true:
      • while loop: Checks the test condition before executing the loop body. If the condition is false initially, the body does not execute.
      • do...while loop: Evaluates the test condition after executing the loop body, guaranteeing at least one execution.
      • for loop: Standard counter-controlled loop with three expressions: initialization, condition evaluation, and increment/decrement step.
      • foreach loop: Iterates specifically over arrays or traversable objects. Extracts elements as foreach ($array as $value) or key-value pairs as foreach ($array as $key => $value).
    • Jump and Execution Control Statements:
      • break: Immediately terminates execution of the nearest enclosing for, foreach, while, do...while, or switch structure.
      • 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.
  • 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 function keyword 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 return statement.
    • 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 use language construct.
    • Arrow Functions: Introduced in modern PHP (PHP 7.4+) as a more concise syntax for simple one-line anonymous functions using the fn keyword, 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).

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"];
    • 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.
  • 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 (returns false if 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)</code>and<code>rtrim(str)</code> and <code>rtrim(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) (or join()): Joins array elements into a single contiguous string separated by the glue string.
  • 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 new keyword, which triggers the class constructor method __construct():
      • Example: $account = new BankAccount();
    • Object Operator (->): The primary operator used to interact with non-static members of an instantiated object:
      • Accessing Properties: Read or write instance variables via object−>propertyName;</code>(notetheabsenceoftheleading<code>object->propertyName;</code> (note the absence of the leading <code> on the property name).
      • Calling Methods: Invoke member functions via object−>methodName(object->methodName(arguments);.
    • 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</code>):</strong>Apseudo−variableavailableinsidenon−staticmethodsthatreferencesthecallingobjectinstance(e.g.,<code>this</code>):</strong> A pseudo-variable available inside non-static methods that references the calling object instance (e.g., <code>this->propertyName).

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 as endif;, endfor;, endforeach;, and endwhile;.
    • Short Echo Tag Integration: Simplifies echoing values inside HTML elements: <h1><?= $pageTitle ?></h1> replaces <h1><?php echo $pageTitle; ?></h1>.
  • Creating Forms and Processing Form Input with User-Defined Arrays

    • HTML Form Setup: HTML <form> elements send user input to a server endpoint via the GET or POST HTTP 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 the name attribute.
      • 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]">
    • Processing Form Arrays in PHP:
      • When submitted, PHP automatically parses input names containing [] and constructs a multi-level array inside the superglobal arrays (POST</code>or<code>_POST</code> or <code>_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() or empty() and traversed iteratively using foreach ($_POST['skills'] as $skill).
  • 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:
      • try block: Encapsulates code that may potentially throw an exception during execution.
      • throw statement: Explicitly triggers an exception, generating an instance of the Exception class (or a subclass): throw new Exception("Invalid input detected");.
      • catch block: Intercepts and handles the thrown exception object. Multiple catch blocks can be chained to handle different exception classes individually.
      • finally block: An optional block placed after catch blocks 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 Exception Class:
      • $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 4 kB4\,kB) 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);
    • 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 to 0 or 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 to true, the cookie is only transmitted over encrypted HTTPS connections.
      • httponly: A boolean value; if set to true, the cookie cannot be accessed by client-side scripts (such as JavaScript document.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 PHPSESSID cookie, 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</code>(e.g.,<code>_SESSION</code> (e.g., <code>_SESSION['user_id'] = 42;).
  • 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 $_SESSION superglobal 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 $_SESSION superglobal for the remainder of the active script execution, nor does it delete the PHPSESSID cookie 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, execute setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]); using parameters fetched via session_get_cookie_params().
      • Step 4: Erase the physical server-side session record via session_destroy();.

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();).
    • 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.
    • 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−>autocommit(false)</code>,<code>mysqli->autocommit(false)</code>, <code>mysqli->commit(), and $mysqli->rollback().
    • PHP Version Support and Deprecation Status:

      • MySQL: Deprecated in PHP 5.5.0 (emits E_DEPRECATED warnings) and officially removed in PHP 7.0.0. Scripts relying on mysql_* functions cannot run on modern PHP versions.
      • MySQLi: Actively maintained, supported, and included by default across PHP 5, PHP 7, and PHP 8 releases.