Build PHP Category Pages with Parent & Child Categories
In this article
This guide shows you how to build PHP category pages that display a parent category and its child categories, with links to each. You'll learn to structure your database, write the PHP to fetch and display the hierarchy, and handle common pitfalls. This is useful for e-commerce, blogs, or any content site that organizes items into nested categories.
What You'll Need
- A web server with PHP (version 7.4 or newer recommended) and MySQL/MariaDB.
- Basic knowledge of PHP, SQL, and HTML.
- Access to your database (phpMyAdmin, command line, or a similar tool).
Step-by-Step
-
Design the database table.
Create a table named
categorieswith at least these columns:id– INT, primary key, auto-increment.name– VARCHAR(255), the category name.slug– VARCHAR(255), a URL-friendly version of the name (e.g., "electronics", "laptops").parent_id– INT, nullable. Set to NULL for top-level categories, or theidof the parent category.
parent_idfor faster queries. -
Insert sample data.
Add a few parent categories (e.g., "Electronics", "Clothing") and child categories (e.g., "Laptops" with
parent_id= 1, "T-Shirts" withparent_id= 2). -
Create a PHP file to fetch categories.
Create a file named
category.php(or any name you prefer). Start by connecting to your database using PDO or mysqli. Example with PDO:$pdo = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password'); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); -
Get the current category from the URL.
Use a query parameter like
?slug=electronicsto identify which category page you're on. Fetch that category from the database:$slug = $_GET['slug'] ?? ''; $stmt = $pdo->prepare('SELECT * FROM categories WHERE slug = ?'); $stmt->execute([$slug]); $category = $stmt->fetch(PDO::FETCH_ASSOC);If no category is found, show a 404 or redirect. -
Determine if it's a parent or child.
If
$category['parent_id']is NULL, it's a parent. If not, it's a child. You'll handle both cases. -
Fetch child categories (if current is a parent).
If the current category is a parent, query for all categories where
parent_idequals the current category'sid:$stmt = $pdo->prepare('SELECT * FROM categories WHERE parent_id = ?'); $stmt->execute([$category['id']]); $children = $stmt->fetchAll(PDO::FETCH_ASSOC); -
Fetch parent category (if current is a child).
If the current category is a child, fetch its parent using the
parent_id:$stmt = $pdo->prepare('SELECT * FROM categories WHERE id = ?'); $stmt->execute([$category['parent_id']]); $parent = $stmt->fetch(PDO::FETCH_ASSOC); -
Display the page.
Start with an HTML header, then show the category name. If it's a parent, list the child categories as links. If it's a child, show a link back to the parent and maybe a breadcrumb. Example:
<h1><?= htmlspecialchars($category['name']) ?></h1> <?php if (!empty($children)): ?> <h2>Subcategories</h2> <ul> <?php foreach ($children as $child): ?> <li><a href="category.php?slug=<?= $child['slug'] ?>"><?= htmlspecialchars($child['name']) ?></a></li> <?php endforeach; ?> </ul> <?php elseif ($parent): ?> <p>Category: <a href="category.php?slug=<?= $parent['slug'] ?>"><?= htmlspecialchars($parent['name']) ?></a></p> <?php endif; ?> -
Handle items within categories (optional).
If you have products or posts, add a
category_idcolumn to that table and fetch items wherecategory_idequals the current category's ID. This is beyond the core scope but follows the same pattern.
Common Mistakes
- Not sanitizing output. Always use
htmlspecialchars()when echoing category names to prevent XSS attacks. - Using
$_GET['slug']without validation. Always check if the parameter exists and is a string. - Forgetting to handle NULL parent_id. If you query for parent_id = NULL, you must use
IS NULLin SQL, not= NULL. - Hardcoding database credentials. Use environment variables or a config file outside the web root.
- Not preparing SQL statements. Use prepared statements to prevent SQL injection.
Tips
- Use a recursive function if you need unlimited depth, but for most sites two levels (parent-child) is enough.
- Cache the category tree if you have many categories to reduce database load.
- Use a URL structure like
/category/electronics/laptopsfor better SEO, but that requires more complex routing. - Add a
sort_ordercolumn to control the display order of child categories. - Consider using a framework like Laravel or Symfony for larger applications, as they handle routing and ORM out of the box.
Troubleshooting
- Page shows "Undefined variable" errors. Make sure you initialize variables like
$childrenand$parentbefore using them (e.g., set them to an empty array or null). - Child categories not showing. Check that the
parent_idin your database matches the parent'sidexactly (no leading zeros). Also verify your SQL query usesWHERE parent_id = ?correctly. - Parent link not working. Ensure the parent's slug is correct and that the query parameter is being passed properly in the URL.
- Database connection fails. Check your credentials, host, and that the database exists. Enable error reporting in PHP to see the exact error.
- Slug contains spaces or special characters. Generate slugs using a function like
strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $name)))and store them in the database.
Frequently Asked Questions
How do I create a slug from a category name?
Use a PHP function that converts the name to lowercase, replaces spaces and non-alphanumeric characters with hyphens, and removes trailing hyphens. Example: $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $name), '-'));
Can I have more than two levels of categories?
Yes, you can support unlimited depth by using a recursive function to fetch all descendants, or by using a nested set model. For most sites, two levels are sufficient, but the same principle applies for deeper hierarchies.
How do I show a breadcrumb navigation?
Fetch the parent chain by repeatedly querying the parent of the current category until you reach a NULL parent_id. Then display the chain in reverse order.
What if a category has no children?
That's fine. Just check if the $children array is empty and display a message like "No subcategories" or simply show the items in that category.
Is it better to use a single table or separate tables for categories and items?
Use a single table for categories, and a separate table for items (products, posts) with a category_id foreign key. This keeps the structure normalized and easy to maintain.
How do I handle categories that are both parent and child?
That's possible. For example, "Electronics" is a child of "Store", but also a parent of "Laptops". Your code should handle both: if it has children, show them; if it has a parent, show a link to it. The logic above already does this.