Skip to content
PHP Logo

What are the advantages of using a centralized database connection class like the one shown in the thread, compared to directly establishing connections in each file?

Using a centralized database connection class allows for better organization and maintenance of database connections in a PHP application. It promotes code reusability, as the database connection logic is encapsulated in one class that can be easily accessed from any part of the application. Additionally, it helps in enforcing best practices such as connection pooling and error handling, leading to more robust and scalable database interactions.

php
<?php
class Database {
    private $host = 'localhost';
    private $username = 'username';
    private $password = 'password';
    private $database = 'database';
    private $connection;

    public function __construct() {
        $this->connection = new mysqli($this->host, $this->username, $this->password, $this->database);

        if ($this->connection->connect_error) {
            die("Connection failed: " . $this->connection->connect_error);
        }
    }

    public function getConnection() {
        return $this->connection;
    }
}

// Example of how to use the centralized database connection class
$database = new Database();
$connection = $database->getConnection();