Home > Article > Backend Development > Prepared Statements for PHP: Identifying the Problem
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!
<?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>
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!