title: Iterating over results of PDO query
body: <p>I want to run a query using PDO, based on data in the URL paramater (yes, I know that this is prone to attacks, but its internal code for a utility). </p>
  
  <pre><code>$user = 'USER';
  $pass = 'PASSWORD';
  $dsn = 'mysql:dbname=PRODUCTS;host=HOST'; 
  
  try {
      $productDB = new PDO($dsn, $user, $pass); 
      $productDB-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  }
  catch(PDOException $e) {
      $msg = 'PDO ERROR' . $e-&gt;getFile() . ' L.' . $e-&gt;getLine() . ' : ' . $e-&gt;getMessage();
      die($msg);
  }
  if(isset($_GET['cat'])) 
  {
      $cat = $_GET['cat'];
      print "cat = $cat &lt;br&gt;";
      $products = $productDB-&gt;prepare('SELECT * FROM products WHERE cat_id LIKE ?');
      $products-&gt;execute(array($cat));
      $rows = $products-&gt;rowCount();
      print "$rows rows returned";
  ?&gt;
  &lt;table border="1"&gt;
  &lt;tr&gt;
      &lt;td&gt;product_id&lt;/td&gt;
      &lt;td&gt;product_name&lt;/td&gt;
  &lt;/tr&gt;
  &lt;?php
  foreach ($products-&gt;fetchAll() as $row) {
      $id = $row['product_id'];
      $product_name = $row['product_name'];
      print "&lt;tr&gt;";
      print "&lt;th scope=\"row\"&gt;&lt;b&gt;$id&lt;/b&gt;&lt;/th&gt;";
      print "&lt;td&gt; $product_name &lt;/td&gt;";
      print "&lt;tr&gt;";
      }
  print "&lt;/table&gt;";
  }
  ?&gt;
  </code></pre>
  
  <p>When I run this code, it prints the correct number of rows depending on the query, but does not populate the table.</p>
  
  <p>I have also tried replacing the <code>prepare</code> and <code>execute</code> lines with:</p>
  
  <pre><code>$products = $productDB-&gt;query("SELECT * FROM products WHERE cat_id LIKE $cat");
  </code></pre>
  
  <p>Which returns the correct row count, but doesn't otherwise help.</p>
  
  <p>And finally, I've tried replacing the foreach line with something like:</p>
  
  <pre><code>$rows = $products-&gt;fetchAll();
  foreach ($rows as $row) {
  </code></pre>
  
  <p>My attempts to do the same with a fixed query all work fine, but I am having trouble working out how to place a variable element in a query, and then iterate over the results.</p>