Module 29: PHP and MySQL Application DevelopmentIntermediate50 min read
Relational Modeling, Indexing, Pagination & Solving the N+1 Query Problem
Design normalized MySQL schemas with foreign keys and B-Tree indexes, implement safe LIMIT/OFFSET or keyset pagination, and eliminate N+1 query bottlenecks.
Key Takeaways & Core Concepts
- FROM users WHERE id = ?
queries inside aforeachloop executes **101 queries**! Fix it with aJOINor eager-loadingWHERE id IN (...)`.
1. Solving the N+1 Query Problem
Fetching 100 posts in 1 query and then running 100 separate SELECT * FROM users WHERE id = ? queries inside a foreach loop executes 101 queries! Fix it with a JOIN or eager-loading WHERE id IN (...).
1. Pagination Offset Calculation
1<?php
2$page = max(1, (int)($_GET['page'] ?? 2));
3$perPage = 10;
4$offset = ($page - 1) * $perPage;
5echo "LIMIT $perPage OFFSET $offset\n";
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
5 lines
Note: Safely clamps page number >= 1 before computing SQL offset.
2. Safe Pagination
Always cast $page = max(1, (int)($_GET['page'] ?? 1)); and bind LIMIT/OFFSET as integers.
Practice & AssessmentPHP Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)