title: Inserting multiple values into multiple columns from an array of data using a PDO prepared statement for MySQL
body: <p>I'm new to PHP and MySQL (and programming in general) and I'm trying to create a generic database handler class called <code>Database_Handler</code> that will help me manage basic things like insert, delete, select, update, etc.</p>
  
  <p>I'm working on a member function to handle insert, currently. In my insert function, I would like to <a href="http://www.php.net/manual/en/pdo.prepared-statements.php" rel="nofollow noreferrer">build a prepared PDO insert statement</a> and execute it.</p>
  
  <p>Assume that somewhere in my application, I have called the insert function as follows:</p>
  
  <pre><code>$table = "books";
  $cols = array('author', 'title', 'pubdate');
  $values = array('Bob Smith', 'Surviving the Zombie Apocalypse', '2010');
  
  $db_handler-&gt;insert($table, $cols, $values);
  </code></pre>
  
  <p>How can I use the data from <code>$table</code>, <code>$cols</code> and <code>$values</code> to build a prepared PDO insert statement? Here's my first effort, based on <a href="https://stackoverflow.com/questions/4629022/how-to-insert-an-array-into-a-single-mysql-prepared-statement-w-php-and-pdo">an answer from "How to insert an array into a single MySQL Prepared statement w/ PHP and PDO"</a>.</p>
  
  <pre><code>public function insert($table, $cols, $values){
  
          $numvalues = count($values);
  
          $placeholder = array();
          for($i=0; $i&lt;$numvalues; $i++)
          $placeholder[$i] = '?';
  
          $sql = 'INSERT INTO '. $table . '(' . implode(",", $cols) . ') ';
          $sql.= 'VALUES (' . implode("," $placeholder) . ')"';
  
          $stmt = $this-&gt;dbh-&gt;prepare($sql);
          $for($i=0; $i&lt;$numvalues; $i++)
              $stmt-&gt;bindParam($i+1, $values[$i])
          $stmt-&gt;execute();
  }
  </code></pre>
  
  <p>I don't think this will work, but maybe it will give you an idea of what I want to do. I'm a little confused because the <a href="http://www.php.net/manual/en/pdo.prepared-statements.php" rel="nofollow noreferrer">example given on the php.net manual</a> is: </p>
  
  <pre><code>$stmt = $dbh-&gt;prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
  $stmt-&gt;bindParam(1, $name);
  $stmt-&gt;bindParam(2, $value);
  
  // insert one row
  $name = 'one';
  $value = 1;
  $stmt-&gt;execute();
  </code></pre>
  
  <p>It seems like they are sending <code>$name</code> as a parameter to the <code>bindParam()</code> funciton, then assigning a value to <code>$name</code> afterwards? What is the value of <code>$name</code> when it's sent to <code>bindParam()</code>? Or does <code>bindParam()</code> just associate a parameter with a variable, without taking that variable's data - allowing <code>execute()</code> to handle that part?</p>