Are there any best practices for handling database connections in PHP applications?

Database connections in PHP applications should be handled efficiently to prevent issues such as connection leaks and performance degradation. It is recommended to use connection pooling, limit the number of connections opened simultaneously, and properly close connections after use to free up resources.

// Create a function to establish a database connection
function getDBConnection() {
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "database";

    $conn = new mysqli($servername, $username, $password, $dbname);

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

    return $conn;
}

// Example of using the function to get a database connection
$conn = getDBConnection();

// Close the connection after use
$conn->close();