The Problem with PHP’s Prepared Statements


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

<?php

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');
   $stmt->execute();

   $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">
<head>
   <meta charset="utf-8">
   <title>untitled</title>
</head>
<body>
<?php foreach ($results as $row) : ?>

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

Leave a Reply

Your email address will not be published. Required fields are marked *