Join InMotion Hosting for $3.49/mo & get a year on Tuts+ FREE (worth $180). Start today.

The Problem with PHP's Prepared Statements


Want a free year on Tuts+ (worth $180)? Start an InMotion Hosting plan for $3.49/mo.

PHP's prepared statements (for database access) are fantastic. Not only do they help secure your database queries, but they're also particularly more efficient for larger products. However, there are a couple issues that appear to make these methods less flexible than we'd hope. For one, we must utilize the bind_result method, and pass in a specific number of variables. However, what happens when this code is within a class, and we won't immediately know how many variables to pass? Luckily, there's a solution! I'll show you what it is in today's video tutorial.

Final Code


function read()
   $parameters = array();
   $results = array();

   $mysql = new mysqli('localhost', 'root', 'root', 'db') or die('There was a problem connecting to the database');
   $stmt = $mysql->prepare('SELECT body FROM posts') or die('Problem preparing query');

   $meta = $stmt->result_metadata();

   while ( $field = $meta->fetch_field() ) {

     $parameters[] = &$row[$field->name]; 

   call_user_func_array(array($stmt, 'bind_result'), $parameters);

   while ( $stmt->fetch() ) {
      $x = array();
      foreach( $row as $key => $val ) {
         $x[$key] = $val;
      $results[] = $x;

   return $results;


$results = read();
<!DOCTYPE html>

<html lang="en">
   <meta charset="utf-8">
<?php foreach ($results as $row) : ?>

   <p> <?php echo $row['body']; ?> </p>
<?php endforeach; ?>