I've found this similar question although I haven't been able to wrap my head around the chosen answer, or determine if it even applies to my situation.
I have the following tables for an image gallery:
CREATE TABLE image_categories (
cat_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
parent_id INTEGER UNSIGNED DEFAULT NULL,
title VARCHAR(100) NOT NULL,
valid TINYINT(1) UNSIGNED NOT NULL DEFAULT 1,
PRIMARY KEY(cat_id),
FOREIGN KEY (parent_id)
REFERENCES image_categories(cat_id)
);
CREATE TABLE image_gallery (
img_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
cat_id INTEGER UNSIGNED NOT NULL,
fname CHAR(45) NOT NULL,
title VARCHAR(100) DEFAULT NULL,
description VARCHAR(256) DEFAULT NULL,
create_date DATETIME NOT NULL,
valid TINYINT(1) UNSIGNED NOT NULL DEFAULT 1,
PRIMARY KEY(img_id),
FOREIGN KEY (cat_id)
REFERENCES image_categories(cat_id)
);
Similar to a file tree directory, categories are like folders in that they can have children, and those children can have more children creating an infinite hierarchy.
Given a specific cat_id
I can pull the images as follows:
$sql = "SELECT * FROM image_gallery WHERE cat_id = :cat_id AND valid = TRUE";
$sth = $this->db->prepare($sql);
$sth->execute(array(':cat_id' => $cat_id));
$images = array();
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$images[$row['img_id']]['cat_id'] = $row['cat_id'];
$images[$row['img_id']]['fname'] = $row['fname'];
$images[$row['img_id']]['title'] = $row['title'];
$images[$row['img_id']]['description'] = $row['description'];
$images[$row['img_id']]['create_date'] = $row['create_date'];
$images[$row['img_id']]['valid'] = $row['valid'];
}
What I would like to do, however, is pull the images for the specified category in addition to any sub-categories until no more sub-categories are found.
How can I achieve those results? Either with a modified query or some type of recursive function?