How can the code be modified to improve error detection and reporting, especially when dealing with database connections?

To improve error detection and reporting when dealing with database connections, you can implement error handling using try-catch blocks. This allows you to catch any exceptions that may occur during database operations and handle them appropriately, such as logging the error or displaying a user-friendly message.

<?php
// Database connection parameters
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

try {
    // Create connection
    $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();
}
?>