Lesson 7: Programming for the Web II

Architecture & Databases

⏱️ 60 minutes 🌐 Year 12 Priority 🎯 HSC Critical πŸ—„οΈ SQL Focus

πŸ“– Introduction

This lesson covers web architecture: client-side (front-end) vs server-side (back-end) development, databases, and how they work together in modern web applications.

Web Architecture Layers:
  • Client-side: HTML, CSS, JavaScript (runs in browser)
  • Server-side: Python, Node.js (runs on server)
  • Database: Persistent data storage

🎯 Study Priority Guide

This lesson covers multiple topics with varying importance for your HSC exam. Use this guide to allocate your study time effectively:

⭐⭐⭐⭐⭐ TIER 1: Critical - Must Master

πŸ—„οΈ SQL Databases (40% of study time)

  • Why it's #1: The syllabus dedicates 7 detailed bullet points to SQL with action verbs like "Apply" and "construct script"
  • What to master: SELECT statements, GROUP BY, WHERE constraints, table JOINs
  • How to study: Practice the Interactive SQL Query Builder and write your own queries
  • Exam relevance: Highly likely to appear as hands-on coding questions
⭐⭐⭐⭐ TIER 2: Very Important (30% of study time)

Topics to understand deeply:

  • πŸ–₯️ Web Development System Elements: Client-side vs server-side architecture, how they connect with databases
  • πŸ”„ Web Request Lifecycle: Request-response cycle, web server software, frameworks, how data flows

These form the foundation for understanding how all pieces fit together.

⭐⭐⭐ TIER 3: Important (20% of study time)

Topics to be familiar with:

  • πŸ”€ ORM vs SQL: Direct syllabus requirement - understand when to use each approach
  • 🎨 CSS Impact: How CSS affects consistency, browser flexibility, and maintenance
⭐⭐ TIER 4: Good to Know (10% of study time)

Contextual knowledge:

  • 🌐 W3C Role: Understanding industry standards and accessibility guidelines
  • βš›οΈ Front-End Libraries/Frameworks: Awareness of React, Vue, Bootstrap, Tailwind
  • πŸ“± PWA UI/UX Principles: Design considerations for accessibility and user experience

These provide important context but are less likely to be deeply tested.

πŸ’‘ Study Strategy: Start with SQL (Tier 1), practice until confident, then move to understanding web architecture (Tier 2). Review Tiers 3-4 for conceptual understanding. When revising before exams, focus 80% of your time on Tiers 1-2.

🌐 The World Wide Web Consortium (W3C)

⭐⭐ TIER 4: Good to Know

W3C is the international standards organization for the web (founded 1994 by Tim Berners-Lee), developing protocols and guidelines for accessibility, interoperability, and evolution of the web.

Key W3C Initiatives

1. Web Accessibility Initiative (WAI)

Develops guidelines for web accessibility covering visual, auditory, physical, speech, cognitive, and neurological disabilities.

πŸ“– WCAG 2.1: Web Content Accessibility Guidelines

Four Core Principles (POUR):

  • Perceivable: Information must be presentable to users in ways they can perceive
    • Provide text alternatives for images (alt text)
    • Captions for videos and audio descriptions
    • Sufficient color contrast for readability
  • Operable: User interface components must be operable
    • All functionality available via keyboard
    • Enough time to read and use content
    • No content that causes seizures (flashing animations)
  • Understandable: Information and operation must be understandable
    • Readable and predictable content
    • Clear navigation and error messages
    • Consistent interface patterns
  • Robust: Content must work with current and future technologies
    • Valid HTML/CSS markup
    • Compatible with assistive technologies (screen readers)

Example: A blind user relies on a screen reader to navigate websites. Without proper alt attributes on images, the screen reader would only say "image" without context. With alt text like <img alt="Shopping cart with 3 items">, the user understands the image's purpose.

2. Internationalization (i18n) Standards

Ensures web support for all languages, scripts, and cultures.

πŸ“– Internationalization Features
  • Unicode (UTF-8): Universal character encoding supporting all languages (English, δΈ­ζ–‡, Ψ§Ω„ΨΉΨ±Ψ¨ΩŠΨ©, ΰ€Ήΰ€Ώΰ€¨ΰ₯ΰ€¦ΰ₯€, etc.)
  • Right-to-Left (RTL) Support: Languages like Arabic and Hebrew read right-to-left
  • Date/Time Formats: Different regions format dates differently (US: MM/DD/YYYY vs Europe: DD/MM/YYYY)
  • Currency and Number Formatting: $1,000.00 (US) vs 1.000,00€ (Germany)
  • Language Tags: HTML lang attribute (<html lang="en">, <html lang="ja">)

3. Web Security and Privacy Standards

4. Machine-Readable Data Formats

Why W3C Standards Matter:
  • Interoperability: Websites work consistently across all browsers (Chrome, Firefox, Safari, Edge)
  • Accessibility: Everyone can access the web, regardless of disability or device
  • Future-Proofing: Standards ensure websites remain functional as technology evolves
  • Developer Efficiency: Shared standards reduce the need for browser-specific code

πŸ–₯️ Web Development System Elements

⭐⭐⭐⭐ TIER 2: Very Important

Modern web applications have three layers: client-side, server-side, and database.

Client-Side (Front-End) Development

Code runs in the user's browser. Controls UI, interactivity, and presentation.

The Three Core Technologies

HTML (Structure)

What it does: Defines the content and structure of the webpage

  • Headings, paragraphs, lists
  • Forms, buttons, inputs
  • Images, videos, links
  • Semantic structure
+

CSS (Styling)

What it does: Controls visual appearance and layout

  • Colors, fonts, spacing
  • Layouts (Grid, Flexbox)
  • Animations and transitions
  • Responsive design

JavaScript (Behavior/Interactivity)

What it does: Adds interactivity and dynamic behavior

  • Form validation and submission
  • DOM manipulation (update content without page refresh)
  • AJAX requests (fetch data from server)
  • Event handling (clicks, keyboard input)
  • Animations and dynamic UI updates
πŸ“– Front-End Code Example: User Login Form
HTML (Structure)
<form id="loginForm">
    <label for="email">Email:</label>
    <input type="email" id="email" required>

    <label for="password">Password:</label>
    <input type="password" id="password" required>

    <button type="submit">Log In</button>
</form>
CSS (Styling)
form {
    max-width: 400px;
    padding: 2rem;
    background: white;
    border-radius: 8px;
}

input {
    width: 100%;
    padding: 0.8rem;
    margin: 0.5rem 0;
    border: 1px solid #ccc;
}

button {
    background: #007bff;
    color: white;
    padding: 1rem 2rem;
    border: none;
    cursor: pointer;
}
JavaScript (Behavior)
document.getElementById('loginForm').addEventListener('submit', function(e) {
    e.preventDefault(); // Stop default form submission

    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;

    // Validate inputs
    if (!email.includes('@')) {
        alert('Please enter a valid email address');
        return;
    }

    if (password.length < 8) {
        alert('Password must be at least 8 characters');
        return;
    }

    // Send login request to server
    fetch('/api/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            window.location.href = '/dashboard';
        } else {
            alert('Invalid credentials');
        }
    });
});

Server-Side (Back-End) Development

Code runs on the web server. Handles business logic, database operations, authentication, and dynamic content generation.

Common Server-Side Languages & Frameworks

Language Popular Frameworks Use Cases
Python Django, Flask, FastAPI Data-driven apps, machine learning integration, rapid prototyping
JavaScript (Node.js) Express.js, NestJS, Next.js Real-time apps (chat), APIs, full-stack JavaScript development
PHP Laravel, Symfony, WordPress Content management systems, traditional web apps
Java Spring Boot, Jakarta EE Enterprise applications, banking systems, high-traffic sites
Ruby Ruby on Rails Rapid web application development, startups

Server-Side Responsibilities

πŸ“– Back-End Code Example: User Login (Python/Flask)
Python (Flask) - Server-Side Login Handler
from flask import Flask, request, jsonify
from werkzeug.security import check_password_hash
import sqlite3

app = Flask(__name__)

@app.route('/api/login', methods=['POST'])
def login():
    # Get data from client request
    data = request.get_json()
    email = data.get('email')
    password = data.get('password')

    # Validate inputs (server-side validation is critical!)
    if not email or '@' not in email:
        return jsonify({'success': False, 'error': 'Invalid email'}), 400

    if not password or len(password) < 8:
        return jsonify({'success': False, 'error': 'Invalid password'}), 400

    # Query database for user
    conn = sqlite3.connect('users.db')
    cursor = conn.cursor()
    cursor.execute('SELECT id, password_hash FROM users WHERE email = ?', (email,))
    user = cursor.fetchone()
    conn.close()

    # Check if user exists and password matches
    if user and check_password_hash(user[1], password):
        # Create session (simplified)
        session_token = create_session_token(user[0])
        return jsonify({
            'success': True,
            'token': session_token
        })
    else:
        return jsonify({'success': False, 'error': 'Invalid credentials'}), 401

What's happening here:

  1. Server receives login request from client (front-end)
  2. Extracts email and password from JSON payload
  3. Validates inputs (never trust client-side validation alone!)
  4. Queries SQLite database for user with matching email
  5. Verifies password using secure hashing (never store plain-text passwords!)
  6. If valid, creates session token and sends success response
  7. If invalid, sends error response with 401 Unauthorized status

Interactive Demo: Client-Side vs Server-Side

🎯 Where Does This Code Run?

Click on each code snippet to see whether it runs on the client (browser) or server:

Click a code snippet to check where it runs!
Client-Side vs Server-Side: Key Differences
Aspect Client-Side (Front-End) Server-Side (Back-End)
Runs on User's browser Web server
Languages HTML, CSS, JavaScript Python, Node.js, PHP, Java, Ruby
Purpose User interface, presentation, interactivity Business logic, database operations, authentication
Visible to user? Yes (view source, dev tools) No (hidden from users)
Security Never trust client-side validation (can be bypassed) Secure, validates all inputs
Performance Depends on user's device Depends on server capacity
Database Access No direct access (security risk) Yes, full database access

🎨 Cascading Style Sheets (CSS)

⭐⭐⭐ TIER 3: Important

Controls visual appearance, layout, responsiveness, and animations while separating content (HTML) from presentation.

Why CSS is Critical

1. Consistency of Appearance

Define styles once, apply across thousands of pages. Single CSS rule change updates entire website.

πŸ“– Example: Global Color Change
CSS - Global Style Definition
/* Define brand colors once */
:root {
    --primary-color: #007bff;
    --secondary-color: #6c757d;
    --background: #f8f9fa;
}

/* Apply to all buttons */
button {
    background: var(--primary-color);
    color: white;
}

/* Apply to all headings */
h1, h2, h3 {
    color: var(--primary-color);
}

Result: If the company rebrands and changes the primary color, you only need to update --primary-color once, and all 500 pages update automatically. Without CSS, you'd need to manually edit every HTML file!

2. Responsive Design

Websites adapt to different screen sizes (desktop, tablet, mobile) and orientations.

CSS - Responsive Design with Media Queries
/* Desktop layout (default) */
.container {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr; /* 3 columns */
    gap: 2rem;
}

/* Tablet layout (max-width: 768px) */
@media (max-width: 768px) {
    .container {
        grid-template-columns: 1fr 1fr; /* 2 columns */
    }
}

/* Mobile layout (max-width: 480px) */
@media (max-width: 480px) {
    .container {
        grid-template-columns: 1fr; /* 1 column */
    }
}

3. CSS Maintenance Tools

πŸ“– Sass Example: Variables and Nesting
Sass (preprocessor)
// Define variables
$primary-color: #007bff;
$font-stack: 'Helvetica Neue', sans-serif;

// Nesting (cleaner than standard CSS)
nav {
    background: $primary-color;
    font-family: $font-stack;

    ul {
        list-style: none;
        padding: 0;

        li {
            display: inline-block;
            margin-right: 1rem;

            a {
                color: white;
                text-decoration: none;

                &:hover {
                    text-decoration: underline;
                }
            }
        }
    }
}

Compiled to standard CSS: Sass compiles to browser-compatible CSS, but the source code is much more readable and maintainable.

Best Practices for CSS:
  • Use CSS Variables: Define reusable values (--primary-color, --spacing-large)
  • Mobile-First Design: Design for mobile first, then enhance for larger screens
  • Avoid !important: Only use as a last resort (hard to override)
  • Use Flexbox and Grid: Modern layout systems (avoid floats and tables for layout)
  • Minimize CSS File Size: Minify and compress for faster loading
  • Consistent Naming: Use BEM (Block Element Modifier) or similar naming convention

βš›οΈ Front-End Code Libraries and Frameworks

⭐⭐ TIER 4: Good to Know

Frameworks provide pre-built tools, components, and patterns that speed up development and improve code quality.

JavaScript Frameworks

Complete structure for building single-page applications (SPAs) with routing, state management, and component reusability.

Framework Description Key Features Used By
React JavaScript library for building user interfaces (developed by Facebook/Meta) β€’ Component-based architecture
β€’ Virtual DOM for performance
β€’ JSX syntax (HTML in JS)
β€’ Huge ecosystem
Facebook, Instagram, Netflix, Airbnb
Vue.js Progressive framework for building user interfaces β€’ Easy to learn
β€’ Reactive data binding
β€’ Single-file components
β€’ Flexible and modular
Alibaba, Xiaomi, GitLab
Angular Full-featured framework (developed by Google) β€’ TypeScript-based
β€’ Two-way data binding
β€’ Dependency injection
β€’ Complete solution (routing, forms, HTTP)
Google, Microsoft, IBM
Svelte Compiler-based framework (no virtual DOM) β€’ Compiles to vanilla JS
β€’ Smaller bundle sizes
β€’ Reactive by default
β€’ Simple syntax
Spotify, Apple, The New York Times
πŸ“– React Component Example
React - Counter Component
import React, { useState } from 'react';

function Counter() {
    // State management with hooks
    const [count, setCount] = useState(0);

    return (
        <div>
            <h2>Count: {count}</h2>
            <button onClick={() => setCount(count + 1)}>
                Increment
            </button>
            <button onClick={() => setCount(count - 1)}>
                Decrement
            </button>
            <button onClick={() => setCount(0)}>
                Reset
            </button>
        </div>
    );
}

export default Counter;

Why use React?

  • Reusability: This Counter component can be used anywhere
  • State Management: useState automatically updates UI when count changes
  • Declarative: Describe what the UI should look like, React handles updates
  • Component Composition: Build complex UIs from simple components

CSS Frameworks and Libraries

Pre-designed components and utility classes for faster styling.

Framework Approach Pros Cons
Bootstrap Component-based (pre-designed buttons, cards, modals) Easy to use, responsive grid, extensive documentation Sites look similar, larger file size, requires overrides for customization
Tailwind CSS Utility-first (small classes: flex, text-center, bg-blue-500) Highly customizable, small bundle size (with purging), no naming conflicts Steeper learning curve, HTML can become cluttered with classes
Bulma Flexbox-based, modern and clean Lightweight, easy syntax, responsive Smaller community than Bootstrap
πŸ“– Bootstrap vs Tailwind CSS Comparison
Bootstrap - Component Approach
<button class="btn btn-primary btn-lg">
    Click Me
</button>
Tailwind CSS - Utility Approach
<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
    Click Me
</button>

Bootstrap: Fewer classes, but harder to customize without overriding styles

Tailwind: More classes, but complete control without writing custom CSS

When to Use Frameworks vs Vanilla Code:
  • Use Frameworks When: Building complex SPAs, working in teams, need rapid development, require consistent UI patterns
  • Use Vanilla When: Building simple sites, prioritizing minimal bundle size, learning fundamentals, avoiding dependencies

πŸ”„ The Web Request Lifecycle

⭐⭐⭐⭐ TIER 2: Very Important

How web requests travel from browser to server and back.

Request-Response Cycle

πŸ“– Step-by-Step: Requesting a Webpage

Scenario: User visits https://example.com/products

  1. User Action: User types URL or clicks a link in browser
  2. DNS Lookup: Browser asks DNS server "What's the IP address of example.com?" β†’ Response: 93.184.216.34
  3. TCP Connection: Browser establishes TCP connection with server (3-way handshake)
  4. TLS Handshake: If HTTPS, browser and server negotiate encryption (from Lesson 6!)
  5. HTTP Request Sent: Browser sends GET request:
    HTTP Request
    GET /products HTTP/1.1
    Host: example.com
    User-Agent: Mozilla/5.0
    Accept: text/html
    Cookie: session_id=abc123
  6. Server Receives Request: Web server software (Nginx, Apache) receives request
  7. Server Routes Request: Server determines which application code handles /products
  8. Application Processes Request:
    • Checks authentication (is user logged in?)
    • Queries database for products
    • Applies business logic (filter by category, sort by price)
    • Renders HTML or returns JSON
  9. Database Query: Server executes SQL:
    SQL Query
    SELECT id, name, price, image_url
    FROM products
    WHERE in_stock = TRUE
    ORDER BY price ASC;
  10. HTTP Response Sent: Server sends response back to browser:
    HTTP Response
    HTTP/1.1 200 OK
    Content-Type: text/html
    Content-Length: 4523
    Set-Cookie: session_id=abc123
    
    <!DOCTYPE html>
    <html>
    <head><title>Products</title></head>
    <body>...
  11. Browser Renders Page: Browser parses HTML, loads CSS/JS, displays content to user
  12. Additional Requests: Browser makes separate requests for images, CSS files, JavaScript files

Total time: Typically 50-500 milliseconds, depending on network speed, server location, and complexity

Web Server Software

Handles HTTP requests, serves static files, routes dynamic requests to application code.

Web Server Description Strengths
Nginx High-performance, asynchronous web server Excellent for serving static files, reverse proxy, load balancing
Apache Mature, feature-rich web server Highly configurable, extensive module ecosystem
Node.js (Express) JavaScript runtime serving as web server Real-time applications, full JavaScript stack
Caddy Modern web server with automatic HTTPS Easy configuration, automatic SSL certificate management
Common Architecture: Nginx + Application Server

Many production setups use Nginx as a reverse proxy in front of an application server:

  • Nginx: Handles incoming requests, serves static files (images, CSS, JS), terminates SSL
  • Application Server: Runs Python/Node.js/PHP code, processes business logic, queries database
  • Benefit: Nginx efficiently handles thousands of concurrent connections while application servers focus on dynamic content

πŸ—„οΈ SQL Databases

⭐⭐⭐⭐⭐ TIER 1: Critical - Must Master

Standard language for managing relational databases. Stores user accounts, products, orders, and persistent data.

Essential SQL Operations

1. SELECT: Retrieving Data

SQL - Basic SELECT
-- Get all columns from students table
SELECT * FROM students;

-- Get specific columns
SELECT first_name, last_name, email FROM students;

-- Get unique values (no duplicates)
SELECT DISTINCT course_name FROM courses;

2. WHERE: Filtering Results

SQL - WHERE Clause
-- Students with GPA above 3.5
SELECT * FROM students WHERE gpa > 3.5;

-- Students in a specific course
SELECT * FROM students WHERE course = 'Software Engineering';

-- Multiple conditions (AND)
SELECT * FROM students WHERE gpa > 3.0 AND year = 12;

-- Multiple conditions (OR)
SELECT * FROM students WHERE course = 'Physics' OR course = 'Chemistry';

-- Pattern matching (LIKE)
SELECT * FROM students WHERE email LIKE '%@gmail.com';

3. ORDER BY and LIMIT: Sorting and Limiting Results

SQL - ORDER BY and LIMIT
-- Sort by GPA (highest first)
SELECT * FROM students ORDER BY gpa DESC;

-- Sort by last name alphabetically
SELECT * FROM students ORDER BY last_name ASC;

-- Get top 5 students by GPA
SELECT * FROM students ORDER BY gpa DESC LIMIT 5;

-- Sort by multiple columns
SELECT * FROM students ORDER BY year DESC, gpa DESC;

4. GROUP BY: Aggregating Data

Groups rows with same values. Aggregate functions: COUNT, SUM, AVG, MAX, MIN.

SQL - GROUP BY with Aggregate Functions
-- Count students in each course
SELECT course, COUNT(*) as student_count
FROM students
GROUP BY course;

-- Average GPA per year level
SELECT year, AVG(gpa) as average_gpa
FROM students
GROUP BY year;

-- Total sales per product
SELECT product_id, SUM(quantity) as total_sold
FROM orders
GROUP BY product_id;

-- Filter grouped results with HAVING
SELECT course, COUNT(*) as student_count
FROM students
GROUP BY course
HAVING COUNT(*) > 10;
WHERE vs HAVING:
  • WHERE: Filters individual rows before grouping
  • HAVING: Filters grouped results after grouping

Example:

-- Get courses with more than 10 students who have GPA > 3.0
SELECT course, COUNT(*) as count
FROM students
WHERE gpa > 3.0           -- Filter BEFORE grouping
GROUP BY course
HAVING COUNT(*) > 10;     -- Filter AFTER grouping

5. JOINs: Combining Data from Multiple Tables

Combine rows from multiple tables based on related columns.

πŸ“– Database Schema Example

Two tables:

students
id name course_id
1Alice101
2Bob102
3Charlie101
courses
id course_name instructor
101Software EngineeringDr. Smith
102PhysicsDr. Johnson
103ChemistryDr. Lee
SQL - INNER JOIN
-- Get student names with their course names
SELECT students.name, courses.course_name
FROM students
INNER JOIN courses ON students.course_id = courses.id;

-- Result:
-- Alice    | Software Engineering
-- Bob      | Physics
-- Charlie  | Software Engineering

Types of JOINs

JOIN Type Returns Use Case
INNER JOIN Only rows with matches in both tables Get students enrolled in courses (excludes students without courses)
LEFT JOIN All rows from left table + matching rows from right table (NULL if no match) Get all students, including those not enrolled in any course
RIGHT JOIN All rows from right table + matching rows from left table (NULL if no match) Get all courses, including those with no students
FULL OUTER JOIN All rows from both tables (NULL where no match) Get all students and all courses, regardless of enrollment
SQL - LEFT JOIN Example
-- Get ALL students, even if they're not enrolled in a course
SELECT students.name, courses.course_name
FROM students
LEFT JOIN courses ON students.course_id = courses.id;

-- Result:
-- Alice    | Software Engineering
-- Bob      | Physics
-- Charlie  | Software Engineering
-- David    | NULL    (David exists in students but has no course_id)

Interactive SQL Query Builder

🎯 Build and Test SQL Queries

Select options below to build a SQL query and see the results:

Your SQL query will appear here...

πŸ”€ ORM vs SQL

⭐⭐⭐ TIER 3: Important

Two approaches: raw SQL queries or Object-Relational Mapping (ORM).

What is an ORM?

Library for database interaction using programming language objects instead of SQL queries. Automatically translates code to SQL.

Without ORM (Raw SQL)

# Python with raw SQL (sqlite3)
import sqlite3

conn = sqlite3.connect('school.db')
cursor = conn.cursor()

# Manual SQL query
cursor.execute('SELECT * FROM students WHERE gpa > ?', (3.5,))
students = cursor.fetchall()

# Manual data processing
for row in students:
    print(f"ID: {row[0]}, Name: {row[1]}, GPA: {row[2]}")

conn.close()

With ORM (SQLAlchemy in Python)

# Python with ORM (SQLAlchemy)
from sqlalchemy import create_engine, Column, Integer, String, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

# Define Student model (represents students table)
class Student(Base):
    __tablename__ = 'students'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    gpa = Column(Float)

# Create database connection
engine = create_engine('sqlite:///school.db')
Session = sessionmaker(bind=engine)
session = Session()

# Query using Python objects (no SQL!)
students = session.query(Student).filter(Student.gpa > 3.5).all()

# Access data like Python objects
for student in students:
    print(f"ID: {student.id}, Name: {student.name}, GPA: {student.gpa}")

ORM vs Raw SQL: Comparison

Aspect Raw SQL ORM (e.g., SQLAlchemy, Django ORM)
Syntax Write SQL strings directly Use Python/JavaScript objects and methods
Learning Curve Must learn SQL syntax Must learn ORM API (but use familiar programming language)
Database Portability SQL syntax varies between databases (PostgreSQL vs MySQL vs SQLite) ORM handles differences, easily switch databases
Performance Can write highly optimized queries ORM-generated queries may be less efficient for complex operations
Security Risk of SQL injection if not using parameterized queries Automatically prevents SQL injection
Code Readability SQL strings mixed with application code Clean, Pythonic/JavaScript-like code
Complex Queries Full SQL power (joins, subqueries, CTEs) Can be verbose or require raw SQL fallback
Schema Management Manual table creation with SQL Migrations automatically generate SQL from model changes
πŸ“– Example: Creating a New Student Record
Raw SQL (Python sqlite3)
cursor.execute(
    'INSERT INTO students (name, email, gpa) VALUES (?, ?, ?)',
    ('John Doe', 'john@example.com', 3.8)
)
conn.commit()
ORM (SQLAlchemy)
new_student = Student(name='John Doe', email='john@example.com', gpa=3.8)
session.add(new_student)
session.commit()

ORM Advantage: More readable, type-safe, and prevents SQL injection automatically.

When to Use Each Approach:
  • Use ORM When: Building CRUD applications, rapid development, working with team (consistent patterns), database portability needed
  • Use Raw SQL When: Complex analytical queries, performance-critical operations, full control needed, legacy database integration
  • Hybrid Approach: Many projects use ORM for most operations but drop to raw SQL for complex reports and optimizations

Popular ORMs by Language

πŸ“± Progressive Web Apps (PWAs): UI/UX Principles

⭐⭐ TIER 4: Good to Know

Combine web and mobile apps for app-like experiences in the browser.

Core UI/UX Design Principles

1. Typography (Fonts)

Affects readability, accessibility, and brand identity.

πŸ“– Typography Best Practices
  • Font Size: Minimum 16px for body text (mobile), 14px for desktop
  • Line Height: 1.5-1.7 for readability (avoid cramped text)
  • Font Pairing: Combine serif (headings) with sans-serif (body) or use single font family
  • Web-Safe Fonts: Use system fonts or web fonts (Google Fonts) with fallbacks
  • Contrast: Sufficient contrast between text and background (WCAG AA: 4.5:1 ratio)

Example:

body {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;
    font-size: 16px;
    line-height: 1.6;
    color: #333;
}

2. Color Theory and Palettes

3. Audio and Video

Requires careful implementation for accessibility and performance.

Audio/Video Best Practices:
  • Autoplay: Never autoplay audio/video (annoying, accessibility issue)
  • Captions: Always provide captions/subtitles for videos (accessibility + SEO)
  • Transcripts: Provide text transcripts for audio content
  • Controls: Always include play/pause, volume, progress bar
  • Optimization: Compress media files, use adaptive streaming for large videos
  • Formats: Provide multiple formats (MP4, WebM) for browser compatibility

4. Navigation Patterns

Navigation Type Description Best For
Top Navigation Bar Horizontal menu at top of page 5-7 main sections, desktop-focused sites
Hamburger Menu Hidden menu revealed by ☰ icon Mobile apps, sites with many sections
Tab Bar (Bottom Nav) Fixed navigation at bottom of screen Mobile apps, 3-5 primary actions
Sidebar Navigation Vertical menu on left/right side Admin dashboards, content-heavy sites
Breadcrumbs Home > Products > Laptops > MacBook E-commerce, deep content hierarchies

Accessibility and Inclusivity

Ensures everyone can use your application, regardless of disability, device, or internet speed.

WCAG Compliance

πŸ“– Essential Accessibility Practices
  • Semantic HTML: Use <button> instead of <div onclick> (screen reader support)
  • Alt Text: Describe images for screen readers (<img alt="Red shopping cart icon">)
  • Keyboard Navigation: All functionality accessible via keyboard (Tab, Enter, Space, Arrow keys)
  • Focus Indicators: Visible outline/highlight when element is focused
  • ARIA Labels: Add descriptive labels for complex UI elements
  • Color Contrast: Minimum 4.5:1 ratio for normal text, 3:1 for large text
  • Skip Links: "Skip to main content" for keyboard users
  • Responsive Text: Allow text resizing up to 200% without breaking layout
  • Form Labels: Every input has a visible <label>
  • Error Messages: Clear, actionable error descriptions
Common Accessibility Mistakes:
  • Using <div> instead of <button> for clickable elements
  • Missing alt text on images
  • Low color contrast (gray text on white background)
  • Relying only on color to convey information (e.g., red = error)
  • Autoplaying videos with sound
  • No keyboard focus indicators
  • Tiny touch targets on mobile (<12px clickable area)

Inclusive Design Principles

The Business Case for Accessibility:
  • Larger Audience: 15% of world population has some form of disability
  • SEO Benefits: Semantic HTML and alt text improve search rankings
  • Legal Compliance: Many countries require accessible websites (ADA in US, EAA in EU)
  • Better UX for Everyone: Accessible design improves usability for all users, not just those with disabilities

πŸ“ Lesson Summary

Key Topics Covered:
  • W3C Standards: Accessibility, internationalization, security, machine-readable data
  • Client-Side: HTML, CSS, JavaScript (browser)
  • Server-Side: Python/Node.js (server logic, database, authentication)
  • CSS: Consistency, responsive design, frameworks
  • Frameworks: React, Vue, Angular, Bootstrap, Tailwind
  • Request Lifecycle: DNS β†’ TCP β†’ HTTP β†’ server β†’ database β†’ response
  • SQL: SELECT, WHERE, ORDER BY, GROUP BY, JOINs
  • ORM vs SQL: Object-oriented vs raw queries
  • PWA UI/UX: Typography, color, navigation, accessibility
HSC Exam Tips:
  • ⭐⭐⭐⭐⭐ PRIORITY: Practice SQL queries with SELECT, WHERE, JOIN, GROUP BY until you can write them confidently
  • Explain why code runs client-side vs server-side (architecture understanding)
  • Understand the complete web request lifecycle from browser to database and back
  • Know when to use ORM vs raw SQL (comparison question)
  • Remember WCAG POUR principles for accessibility
  • Never trust client-side validation (security principle)
πŸ“Š Study Time Allocation:
  • 40%: SQL Databases (Tier 1) - Write actual queries!
  • 30%: Web Architecture & Request Lifecycle (Tier 2)
  • 20%: ORM vs SQL + CSS Impact (Tier 3)
  • 10%: W3C, Frameworks, PWA UI/UX (Tier 4)
Next: Lesson 8 - Software Automation, Machine Learning & AI

DevOps/RPA/BPA, AI vs ML, training models, neural networks, decision trees, ethical implications

← Back to Dashboard