What are best practices for handling database connections in PHP scripts to avoid errors like this?
When handling database connections in PHP scripts, it is best practice to ensure that connections are properly closed after they are no longer needed to avoid errors like "Too many connections" or running out of available connections. One way to achieve this is by using try-catch-finally blocks to ensure that the connection is closed even if an exception is thrown.
<?php
// Database connection parameters
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
try {
// Create connection
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// Set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Perform database operations here
} catch(PDOException $e) {
// Handle any errors
echo "Connection failed: " . $e->getMessage();
} finally {
// Close the connection
$conn = null;
}
?>