title: Dynamic queries with PHP PDO
body: <p>I'm trying to figure out how to convert my history script from mysql_query() to PDO. I have a form with 4 input fields which you can randomly select. Which means there can be 0, 1, 2, 3, 4 fields selected depending on which info you're trying to get.</p>
  
  <p>I've tried to query db like this:</p>
  
  <pre><code>$q = $db-&gt;prepare('SELECT date,
                            name,
                            action
                     FROM history
                     WHERE name = :name
                     AND action = :action');
  
  $q-&gt;bindParam(':name', $Name, PDO::PARAM_STR, 20);
  $q-&gt;bindParam(':action', $Action, $PDO::PARAM_STR, 20);
  $q-&gt;execute();
  </code></pre>
  
  <p>But this doesn't work if I don't have any fields selected and want the whole history shown.</p>
  
  <p>With mysql_query() I'd just do this:</p>
  
  <pre><code>mysql_query('SELECT date,
                      name,
                      action
               FROM history
               $Name
               $Action');
  </code></pre>
  
  <p>Which means if there's no $Name or $Action they're simply not included in the query.</p>
  
  <p>Should I just copy/paste the old query into $q = $db-query('')? But that kind of defeats the purpose of using PDO.</p>