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
Keywords
Related Questions
- How can PHP be used to troubleshoot and debug issues with image display on a website?
- What are the best practices for handling PHP scripts that run for an extended period of time, such as when sending emails to a large mailing list?
- How can you properly set the Content-Type header when serving images in PHP to ensure they are displayed correctly?