Skip to content
PHP Logo

What are the drawbacks of connecting to the database multiple times within the same function in PHP?

Connecting to the database multiple times within the same function can lead to inefficiency and increased resource usage. It is recommended to establish a single database connection and reuse it throughout the function to improve performance and reduce overhead.

php
// Establish a single database connection and reuse it throughout the function

// Create a database connection
$connection = new mysqli("localhost", "username", "password", "database");

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

// Use the $connection object for database operations within the function

// Close the connection at the end of the function
$connection->close();