Home > Backend Development > PHP Tutorial > How to Properly Use a PDO Connection Across Multiple Classes in PHP?

How to Properly Use a PDO Connection Across Multiple Classes in PHP?

Barbara Streisand
Release: 2024-12-21 00:50:08
Original
1015 people have browsed it

How to Properly Use a PDO Connection Across Multiple Classes in PHP?

How to Use PDO Connection in Other Classes?

Understanding the Puzzling Error

An error message stating "Uncaught Error: Call to undefined method Database::prepare()" may arise when attempting to use a PDO connection in a separate class. This error stems from a misunderstanding of how object-oriented programming (OOP) interconnects objects.

Resolving the Issue

1. Rethink Your Database Class:
The existing Database class serves no meaningful purpose. Instead, focus on creating a wrapper class if it extends PDO's functionality.

2. Establish a Central Database Connection:
Instantiate a standalone $db object using PDO or your enhanced database class. This single connection will serve as the cornerstone for all future database activities.

3. Pass the Connection as a Constructor Parameter:
Every class requiring database access should receive the $db connection as a constructor argument. This approach guarantees seamless access to the database throughout your entire application.

A Comprehensive Example

Consider the following improved codebase:

database.php:

$host = '127.0.0.1';
$db   = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
    \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
    \PDO::ATTR_EMULATE_PREPARES   => false,
];
$pdo = new \PDO($dsn, $user, $pass, $opt);
Copy after login

user.php:

class User {
    /* Properties */
    private $conn;

    /* Get database access */
    public function __construct(\PDO $pdo) {
        $this->conn = $pdo;
    }

    /* List all users */
    public function getUsers() {
        return $this->conn->query("SELECT username, usermail FROM user")->fetchAll();
    }
}
Copy after login

app.php:

include 'database.php';
$user = new User($pdo);
$list = $user->getUsers();

foreach($list as $test) {
    echo $test["username"],"\n";
}
Copy after login

This refined codebase exemplifies the correct usage of PDO connections in multiple classes, ensuring error-free operation and elegant coding practices.

The above is the detailed content of How to Properly Use a PDO Connection Across Multiple Classes in PHP?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template