Is it more efficient to establish a new database connection for each SQL query in PHP, or should connections be reused?
Establishing a new database connection for each SQL query in PHP can be inefficient as it incurs overhead in creating and tearing down connections. It is generally more efficient to reuse a single database connection throughout the script execution. This can be achieved by creating a connection object once and then passing it to functions or classes that need to execute queries.
// Create a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Function to execute SQL query using the existing connection
function executeQuery($conn, $sql) {
$result = $conn->query($sql);
if ($result === FALSE) {
echo "Error: " . $conn->error;
}
return $result;
}
// Example usage
$sql = "SELECT * FROM table_name";
$result = executeQuery($conn, $sql);
// Close the connection at the end of the script
$conn->close();