What are best practices for handling database connections in PHP to avoid errors like "Unable to connect to server"?
When handling database connections in PHP, it is important to properly handle potential errors such as "Unable to connect to server". One way to avoid this issue is to use try-catch blocks when establishing the database connection. This allows you to catch any exceptions that may occur during the connection process and handle them accordingly.
<?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();
}
?>
Keywords
Related Questions
- What are some common ways to align images and text using PHP?
- How can the array key be utilized as a counter in PHP to simplify iteration and output?
- Are there alternative approaches or design patterns in PHP that can be used instead of switch statements for including different pages based on conditions?