What steps can be taken to display database errors in PHP for testing purposes?

When testing a PHP application that interacts with a database, it is important to display database errors for debugging purposes. To do this, you can set the error reporting level to display all errors, enable error logging, and use try-catch blocks to catch and display any database errors that occur.

// Set error reporting level to display all errors
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Enable error logging
ini_set('log_errors', 1);
ini_set('error_log', '/path/to/error.log');

// Connect to the database
$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);
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}