What are the best practices for handling connection errors in PHP scripts?
When handling connection errors in PHP scripts, it is important to use try-catch blocks to catch exceptions and handle them gracefully. This allows you to provide meaningful error messages to users and log detailed information for debugging purposes. Additionally, you can use functions like mysqli_connect_errno() and mysqli_connect_error() to retrieve specific error codes and messages from database connections.
try {
$db = new mysqli('localhost', 'username', 'password', 'database');
if ($db->connect_error) {
throw new Exception('Connection failed: ' . $db->connect_error);
}
// Proceed with database operations
} catch (Exception $e) {
// Handle connection error
echo 'Error: ' . $e->getMessage();
}