title: Are Dynamic Prepared Statements Bad? (with php + mysqli)
body: <p>I like the flexibility of Dynamic SQL and I like the security + improved performance of Prepared Statements.  So what I really want is Dynamic Prepared Statements, which is troublesome to make because bind_param and bind_result accept "fixed" number of arguments.  So I made use of an eval() statement to get around this problem.  But I get the feeling this is a bad idea.  Here's example code of what I mean</p>
  
  <pre><code>// array of WHERE conditions
  $param = array('customer_id'=&gt;1, 'qty'=&gt;'2');
  $stmt = $mysqli-&gt;stmt_init();
  
  $types = ''; $bindParam = array(); $where = ''; $count = 0;
  
  // build the dynamic sql and param bind conditions
  foreach($param as $key=&gt;$val)
  {
      $types .= 'i';
      $bindParam[] = '$p'.$count.'=$param["'.$key.'"]'; 
      $where .= "$key = ? AND ";
      $count++;
  }
  
  // prepare the query -- SELECT * FROM t1 WHERE customer_id = ? AND qty = ?
  $sql = "SELECT * FROM t1 WHERE ".substr($where, 0, strlen($where)-4);
  $stmt-&gt;prepare($sql);
  
  // assemble the bind_param command
  $command = '$stmt-&gt;bind_param($types, '.implode(', ', $bindParam).');';
  
  // evaluate the command -- $stmt-&gt;bind_param($types,$p0=$param["customer_id"],$p1=$param["qty"]);
  eval($command);
  </code></pre>
  
  <p>Is that last eval() statement a bad idea?  I tried to avoid code injection by encapsulating values behind the variable name $param.</p>
  
  <p>Does anyone have an opinion or other suggestions?  Are there issues I need to be aware of?</p>