What are the best practices for establishing and managing database connections in PHP scripts to avoid redundant code and maintain efficiency?

Establishing and managing database connections in PHP scripts can be streamlined by creating a separate database connection file that can be included in all scripts requiring database access. This helps avoid redundant code and ensures consistency in connection settings. Additionally, using a singleton pattern to manage the database connection can help maintain efficiency by reusing the same connection throughout the script execution.

// database_connection.php

class Database {
    private static $instance = null;
    private $connection;

    private function __construct() {
        $this->connection = new mysqli('localhost', 'username', 'password', 'database_name');
    }

    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance->connection;
    }
}

// To use the database connection in your PHP scripts:
// Include the database connection file
require_once 'database_connection.php';

// Get the database connection instance
$connection = Database::getInstance();

// Use the connection to query the database
$result = $connection->query("SELECT * FROM table_name");