What are the best practices for handling database connections in PHP scripts to avoid redundant connections?

To avoid redundant database connections in PHP scripts, it is recommended to use a singleton pattern to create a single instance of the database connection and reuse it throughout the script execution. This helps in reducing the overhead of establishing multiple connections and improves the performance of the application.

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

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

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

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

// Example of how to use the singleton pattern to get the database connection
$db = Database::getInstance();
$connection = $db->getConnection();