title: PDO recursive query
body: <p>I've found this <a href="https://stackoverflow.com/questions/20215744/mysql-hierarchical-recursive-query">similar question</a> although I haven't been able to wrap my head around the chosen answer, or determine if it even applies to my situation.</p>
  
  <p>I have the following tables for an image gallery:</p>
  
  <pre><code>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)
  );
  </code></pre>
  
  <p>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.</p>
  
  <p>Given a specific <code>cat_id</code> I can pull the images as follows: </p>
  
  <pre><code>$sql = "SELECT * FROM image_gallery WHERE cat_id = :cat_id AND valid = TRUE";
  $sth = $this-&gt;db-&gt;prepare($sql);
  $sth-&gt;execute(array(':cat_id' =&gt; $cat_id));
  
  $images = array();
  while ($row = $sth-&gt;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'];
  }
  </code></pre>
  
  <p>What I would like to do, however, is pull the images for the specified category <em>in addition to</em> any sub-categories until no more sub-categories are found.</p>
  
  <p>How can I achieve those results? Either with a modified query or some type of recursive function?</p>