What are best practices for handling MySQL connection errors in PHP code?
When handling MySQL connection errors in PHP code, it is important to check for errors after establishing the connection and handle them gracefully. One common approach is to use try-catch blocks to catch any exceptions that may occur during the connection process and display an appropriate error message to the user.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
try {
$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);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Related Questions
- What potential issues could arise with the session management in the provided PHP login script?
- What are the common pitfalls to avoid when working on a custom CMS in PHP, especially in relation to session management?
- Can PDO bindParam statements be combined into a single line for multiple placeholders in a SQL query?