Home > Backend Development > PHP Tutorial > Prepared Statements for PHP: Identifying the Problem

Prepared Statements for PHP: Identifying the Problem

WBOY
Release: 2023-08-30 08:30:01
Original
895 people have browsed it

PHP 的准备语句:识别问题

PHP's prepared statements (for database access) are great. Not only do they help protect your database queries, but they are especially more effective for larger products. However, there are some issues that seem to make these methods less flexible than we would like. First, we have to use the bind_result method and pass in a specific number of variables. But what happens when this code is in a class and we don't immediately know how many variables to pass? Fortunately, there is a solution! I'm going to show you what it is in today's video tutorial.

Premium members: Download this video (must log in)

Subscribe to our YouTube page to watch all video tutorials!


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>
Copy after login

The above is the detailed content of Prepared Statements for PHP: Identifying the Problem. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template