How can you ensure that only one MySQL connection is established and used within a single request in PHP?

To ensure that only one MySQL connection is established and used within a single request in PHP, you can utilize a singleton pattern to create a single instance of the database connection object and reuse it throughout the request. This approach helps prevent multiple connections from being opened and closed unnecessarily, improving performance and resource usage.

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 self();
        }
        return self::$instance;
    }

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

// Example usage
$db = Database::getInstance();
$connection = $db->getConnection();
// Use $connection to perform database operations