What are the best practices for handling MySQL connection errors in PHP scripts?
When handling MySQL connection errors in PHP scripts, it is essential to use error handling techniques such as try-catch blocks to gracefully handle exceptions and provide appropriate error messages to the user. Additionally, it is recommended to log the errors for debugging purposes and to prevent exposing sensitive information to the end-users.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
// Log the error for debugging
error_log("Connection failed: " . $e->getMessage(), 0);
}
?>