13.2 Server-Side Processing, Dynamic Websites, and Databases

Key Takeaways

  • Dynamic web applications process logic, query relational databases, and assemble HTML templates on the web server before transmitting completed responses to clients.
  • PHP (Hypertext Preprocessor) executes server-side, parsing embedded code blocks and reading HTTP superglobals such as $_GET and $_POST.
  • Relational Database Management Systems (RDBMS) organize data into structured tables linked by primary and foreign keys, manipulated using SQL CRUD commands.
  • SQL Injection (SQLi) attacks occur when unsanitized user inputs manipulate SQL query syntax, and are mitigated through PDO prepared statements with parameterized queries.
  • Because HTTP is a stateless protocol, persistent user authentication and sessions rely on server-side session stores linked to unique client session cookies.
Last updated: September 2026

13.2 Server-Side Processing, Dynamic Websites, and Databases

While client-side scripting enhances the responsiveness and presentation of web pages inside the user's browser, large-scale web applications—such as school learning management systems, online course portals, and digital libraries—require persistent storage, secure credential authentication, and centralized business logic. These capabilities are governed by server-side web architecture, wherein remote web servers execute scripts, query relational databases, and dynamically construct HyperText Markup Language (HTML) documents before transmitting them across the network.


Static vs. Dynamic Web Architecture

The World Wide Web accommodates two fundamental architectural paradigms for content delivery: static and dynamic.

STATIC ARCHITECTURE:
Client Browser  <=== HTTP Request (e.g., about.html) ===   Web Server (Apache/Nginx)
                === HTTP Response (Flat HTML/CSS) ===>   (Reads directly from Disk)

DYNAMIC ARCHITECTURE:
Client Browser  <=== HTTP Request (e.g., grades.php) ==   Web Server
                                                                |
                                                     Application Runtime (PHP)
                                                                |
                                                     Database Engine (MySQL)
                                                                |
Client Browser  === Synthesized HTML Response =======   Web Server Assembles Page

1. Static Web Architecture

In a static website, files (HTML, CSS, JavaScript, images, and audio assets) exist as pre-rendered flat files residing on the web server's filesystem or a Content Delivery Network (CDN) edge cache. When a client requests index.html, the web server simply locates the file on storage disk and streams the identical byte sequence back to the browser.

  • Advantages: Outstanding performance and minimal time-to-first-byte (TTFB), minimal server compute overhead, low hosting costs, and virtually zero attack surface for database injection or server-side script exploits.
  • Disadvantages: Content updates require modifying and re-uploading individual files. Managing thousands of catalog pages becomes unmaintainable without automated static site generators, and real-time user personalization or authenticated data access is impossible.

2. Dynamic Web Architecture

In a dynamic website, pages do not exist as static HTML files on disk. Instead, when an HTTP request arrives, the web server passes the request to an application interpreter (such as PHP, Python, or Node.js). The application executes business logic, communicates with a Relational Database Management System (RDBMS) to fetch relevant records, injects the data into structural HTML templates, and synthesizes a fresh HTML document on-the-fly to return to the client.

  • Advantages: Effortless scalability across millions of unique pages, centralized content management, user authentication, interactive form workflows, and custom data views tailored to specific user permissions.
  • Disadvantages: Higher server resource requirements (CPU, RAM), increased database latency, and a larger security profile requiring rigorous protection against injection attacks.

Client-Side vs. Server-Side Execution Model

Understanding where code executes is a core requirement of web application architecture:

  • Client-Side Code (JavaScript, CSS, HTML) executes inside the user's local web browser environment. The source code is completely visible to any user who selects "View Page Source" or opens developer tools. It operates within a browser sandbox with restricted access to the local machine's filesystem.
  • Server-Side Code (PHP, SQL, Python) executes entirely on the remote host server. The client never sees the underlying PHP script or database connection strings; the client receives only the final rendered HTML/CSS output produced by the server. Server-side code enjoys access to backend databases, local filesystems, server APIs, and cryptographic functions.

Server-Side Scripting Fundamentals with PHP

PHP (Hypertext Preprocessor) is an open-source, server-side scripting language specifically engineered for web development. Because PHP interpreter modules integrate directly into web servers like Apache and Nginx, PHP code can be embedded directly alongside standard HTML markup.

PHP Syntax and Embedding

PHP code blocks are encapsulated within special delimiting tags: <?php and ?>. Any code outside these tags is treated by the server as raw HTML and streamed directly to the output buffer without evaluation:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Student Portal</title>
</head>
<body>
  <?php
    // Variable declarations always begin with a dollar sign ($)
    $studentName = "Jordan";
    $gradeLevel = 10;
    $isEnrolled = true;
    
    // Outputting text to the rendered HTML stream
    echo "<h1>Welcome, " . $studentName . "!</h1>";
    echo "<p>Current Grade: " . $gradeLevel . "th Grade</p>";
  ?>
</body>
</html>
  • Identifiers: Every PHP variable must begin with a dollar sign ($) followed by a letter or underscore. Variable names are case-sensitive ($score differs from $Score).
  • Statements: Every individual PHP statement must terminate with a semicolon (;). Omitting a semicolon produces a fatal parse error that prevents the page from rendering.
  • String Concatenation: In PHP, strings are concatenated using the period operator (.), rather than the plus operator (+) used in JavaScript.

Processing HTTP Data: $_GET vs. $_POST Superglobals

When a user submits an HTML form or clicks a link with query parameters, the web server packages the inbound data into PHP superglobals—globally accessible associative arrays populated automatically by the runtime:

GET Request Flow:
Browser Form [method="GET"] ---> URL: search.php?keyword=algebra&page=2
                                                |
                                                v
PHP Engine Populates: $_GET['keyword'] = "algebra"; $_GET['page'] = "2";

POST Request Flow:
Browser Form [method="POST"] --> HTTP Body: username=jordan&pass=Secret123
                                 (URL remains: login.php)
                                                |
                                                v
PHP Engine Populates: $_POST['username'] = "jordan"; $_POST['pass'] = "Secret123";
Attribute$_GET Superglobal$_POST Superglobal
Data TransmissionAppended directly to the URL query string (?key=val&key2=val2).Placed in the HTTP request body rather than the URL.
Data VisibilityVisible in the address bar and commonly retained in history and access logs.Not shown in the address bar, but still visible on an unencrypted HTTP connection and potentially recorded by application, proxy, or diagnostic logs; HTTPS provides transport encryption.
Payload CapacityLimited by browser, server, and intermediary URL limits.Limited by server and application configuration, such as PHP's post_max_size; it is not unlimited.
File UploadsCannot support binary file or media uploads.Required for multi-part binary file uploads (enctype="multipart/form-data").
Browser CachingCan be bookmarked, cached, and refreshed without warning.Cannot be safely bookmarked; resubmission prompts a browser confirmation warning.
Appropriate UseSearch queries, pagination toggles, filtering, and content bookmarks (idempotent read actions).User logins, passwords, financial payments, form submissions that alter database state.

Relational Database Management Systems (RDBMS)

A database is an organized collection of structured information stored electronically. While unstructured data can be stored in flat files or NoSQL document stores, the vast majority of web applications rely on Relational Database Management Systems (RDBMS), such as MySQL, MariaDB, PostgreSQL, or SQLite.

Relational Data Architecture

An RDBMS models data across structured two-dimensional grids called tables (relations):

  • Columns (Fields / Attributes): Define specific data categories with strict data types (e.g., INT for integers, VARCHAR(100) for variable-length strings, DECIMAL(10,2) for currency, DATE for timestamps).
  • Rows (Records / Tuples): Individual horizontal entries within a table representing a single coherent data entity.

Keys and Referential Integrity

Relational databases maintain data accuracy and prevent redundancy through structured keys:

  1. Primary Key (PK): A field (or combination of fields) that uniquely identifies each record in a table. A primary key must be unique, non-null, and immutable (e.g., student_id). Most tables utilize an automatically incrementing integer (AUTO_INCREMENT) as their synthetic primary key.
  2. Foreign Key (FK): A field in one table that points directly to the primary key of another table. Foreign keys establish relational connections (one-to-one, one-to-many, or many-to-many) and enforce referential integrity, ensuring that a record in a child table cannot reference a nonexistent parent record.

Structured Query Language (SQL) and CRUD Operations

Structured Query Language (SQL) is the universal declarative programming language used to define, query, and manipulate data within an RDBMS. Web applications interact with databases by issuing CRUD operations:

  C - CREATE  ====>  INSERT INTO table (columns) VALUES (values)
  R - READ    ====>  SELECT columns FROM table WHERE condition
  U - UPDATE  ====>  UPDATE table SET column = value WHERE condition
  D - DELETE  ====>  DELETE FROM table WHERE condition

1. CREATE: The INSERT Statement

Inserts brand-new records into a specified table:

INSERT INTO students (first_name, last_name, email, grade_level)
VALUES ('Marcus', 'Vance', 'mvance@district.org', 11);

2. READ: The SELECT Statement

Queries and retrieves records matching specific criteria:

SELECT first_name, last_name, email 
FROM students 
WHERE grade_level = 11 
ORDER BY last_name ASC;
  • Using SELECT * retrieves all columns, which is discouraged in production because it consumes unnecessary memory and network bandwidth.

3. UPDATE: The UPDATE Statement

Modifies existing data values within one or more records:

UPDATE students 
SET email = 'marcus.v@district.org' 
WHERE student_id = 42;
  • Critical Safeguard: Always include a specific WHERE clause. Omitting the WHERE clause causes the database to update every single record in the entire table with the specified value.

4. DELETE: The DELETE Statement

Permanently purges records from a table:

DELETE FROM students 
WHERE student_id = 42;
  • Critical Safeguard: As with UPDATE, omitting the WHERE clause permanently deletes every record in the table.

Database Connectivity, Security, and Vulnerability Mitigation

In modern PHP development, connecting to a MySQL database is accomplished through PHP Data Objects (PDO), an object-oriented database abstraction layer that provides uniform methods for querying different database engines.

The Anatomy of a SQL Injection (SQLi) Attack

SQL Injection is one of the most devastating security vulnerabilities in web applications. It occurs when untrusted user input is directly concatenated into a raw SQL query string without sanitization. An attacker supplies malicious SQL fragments that manipulate the query's logical structure:

// DANGEROUS VULNERABILITY: Direct string concatenation
$userEmail = $_POST['email']; // Attacker enters: ' OR '1'='1
$query = "SELECT * FROM users WHERE email = '" . $userEmail . "'";
// Rendered SQL: SELECT * FROM users WHERE email = '' OR '1'='1'

Because '1'='1' is always true, the database returns all user records in the system, completely bypassing password checks and permitting administrative takeover.

Mitigating SQLi: Prepared Statements and Parameterized Queries

The primary defense against SQL injection through data values is prepared statements with parameterized queries. They must be used correctly: placeholders represent values, not table names, column names, sort directions, or arbitrary SQL fragments. Dynamic identifiers require a strict allow-list, and applications still need least-privilege database accounts, safe error handling, and appropriate validation. A prepared statement separates two phases:

  1. Preparation: The web application transmits the SQL query template containing placeholders (such as :email or ?) to the database server. The database engine parses, compiles, and optimizes the query structure before any user data is introduced.
  2. Parameter Binding and Execution: The application binds the user-supplied values strictly as parameters to the placeholders and executes the query.
// SECURE IMPLEMENTATION: PDO Prepared Statement
$pdo = new PDO("mysql:host=localhost;dbname=school_db;charset=utf8mb4", "db_user", "secure_pass");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// 1. Prepare query structure with named placeholder :email
$stmt = $pdo->prepare("SELECT user_id, password_hash, role FROM users WHERE email = :email");

// 2. Bind parameter and execute securely
$stmt->execute(['email' => $_POST['email']]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

Because the database engine has already compiled the SQL statement, it treats the bound parameter strictly as a literal data string, never as executable code. Even if an attacker enters ' OR '1'='1, the database searches literally for a user whose email address is equal to the characters ' OR '1'='1, completely neutralizing the injection attempt.

Defending Against Cross-Site Scripting (XSS)

When displaying data retrieved from a database back onto an HTML page, developers must encode special HTML characters to prevent stored XSS attacks:

// Encodes characters like <, >, &, and quotes into HTML entities (&lt;, &gt;)
echo "<p>Author: " . htmlspecialchars($user['username'], ENT_QUOTES, 'UTF-8') . "</p>";

User State Management: Cookies vs. Sessions

The fundamental protocol of the web, HyperText Transfer Protocol (HTTP), is inherently stateless. This means each request-response transaction is completely isolated; the server retains zero memory of previous requests from the same user. To build persistent applications with user logins and shopping carts, developers must employ state management techniques.

SESSION ARCHITECTURE:
1. Client logs in with credentials.
2. Server verifies password, creates session on server disk/RAM.
3. Server responds with HTTP header: Set-Cookie: PHPSESSID=x8f93...; HttpOnly; Secure
4. Client stores PHPSESSID cookie.
5. On every subsequent request, browser automatically transmits:
   Cookie: PHPSESSID=x8f93...
6. Server reads PHPSESSID, looks up user data in session store.

1. HTTP Cookies (Client-Side State)

An HTTP cookie is a small text file (up to 4 KB) stored directly in the user's browser by the web server via the Set-Cookie response header. On every subsequent request to that domain, the browser automatically sends the cookie back in the Cookie request header.

  • Security Attributes:
    • HttpOnly: Prevents client-side scripts (JavaScript) from accessing the cookie via document.cookie, mitigating cookie theft through XSS vulnerabilities.
    • Secure: Ensures the cookie is only transmitted across encrypted HTTPS connections.
    • SameSite=Strict / Lax: Protects against Cross-Site Request Forgery (CSRF) by preventing third-party sites from sending the cookie during cross-origin requests.

2. Server-Side Sessions (Server-Side State)

A session stores state data directly on the web server (in memory, files, or a Redis cache), transmitting only an opaque, cryptographically random Session Identifier (Session ID) to the client as a cookie:

// Initializing or resuming a session (must be called before any HTML output)
session_start();

// Storing authenticated user data in the $_SESSION superglobal
$_SESSION['user_id'] = $user['user_id'];
$_SESSION['user_role'] = $user['role'];
$_SESSION['logged_in'] = true;

// Reading session data on subsequent pages
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
  header("Location: login.php");
  exit();
}
echo "Welcome, authorized " . htmlspecialchars($_SESSION['user_role']);

Sessions are vastly more secure than storing raw user credentials in cookies because sensitive data (such as permissions, passwords, and billing information) never leaves the protected server environment.


Web Architecture and Database Operations Reference

Concept / CommandTier / ClassificationTechnical Syntax / RoleSecurity & Architectural Best Practice
Static ArchitectureWeb Server / StoragePre-rendered HTML/CSS flat files on disk.Ideal for high-speed documentation, blogs, and public brochures.
Dynamic ArchitectureApp Server + DatabaseServer parses scripts, queries DB, generates HTML.Mandatory for authenticated portals, real-time data, and e-commerce.
$_GET SuperglobalPHP HTTP Input$_GET['param'] from URL query string.Use only for safe, bookmarkable read queries; never for passwords.
$_POST SuperglobalPHP HTTP Input$_POST['param'] from HTTP request body.Mandatory for user authentication, form submissions, and state mutations.
INSERT INTOSQL (Create)INSERT INTO table (c1, c2) VALUES (?, ?)Always parameterize values to block SQL injection payloads.
SELECTSQL (Read)SELECT c1, c2 FROM table WHERE c1 = ?Explicitly specify required column names rather than using SELECT *.
UPDATESQL (Update)UPDATE table SET c1 = ? WHERE id = ?Always include an explicit WHERE clause to avoid modifying the entire table.
DELETESQL (Delete)DELETE FROM table WHERE id = ?Always enforce strict WHERE conditions and referential integrity checks.
Prepared StatementsDatabase Security$pdo->prepare(); $stmt->execute();Keeps bound values separate from SQL structure; allow-list any identifiers or query fragments that cannot be parameterized.
PHP SessionsState Managementsession_start(); $_SESSION['key'] = val;Keeps application state server-side while the client holds a session identifier; security still requires HTTPS, secure cookie attributes, ID rotation, expiration, and protected storage.
Test Your Knowledge

A web developer discovers that an attacker gained administrative access by entering "' OR '1'='1" into a login email field. What primary architectural technique prevents this value from being interpreted as SQL syntax?

A
B
C
D
Test Your Knowledge

Which of the following scenarios represents the most technically appropriate use of the HTTP GET method and the PHP '$_GET' superglobal?

A
B
C
D
Test Your Knowledge

Because HTTP is an inherently stateless protocol, how does a server-side PHP application maintain persistent user authentication across sequential page requests?

A
B
C
D