How can PHP developers improve error handling and user feedback when dealing with connection failures to external databases like MS-SQL?
When dealing with connection failures to external databases like MS-SQL, PHP developers can improve error handling and user feedback by implementing try-catch blocks to catch exceptions and display meaningful error messages to users. Additionally, developers can use the mysqli_connect_error() function to retrieve detailed error messages from the database connection.
<?php
$serverName = "your_server_name";
$connectionOptions = array(
"Database" => "your_database_name",
"Uid" => "your_username",
"PWD" => "your_password"
);
try {
$conn = sqlsrv_connect($serverName, $connectionOptions);
if (!$conn) {
throw new Exception("Connection failed: " . sqlsrv_errors());
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>