How can the issue of an "invalid data source name" error in PHP be resolved when establishing a database connection?

The "invalid data source name" error in PHP typically occurs when the database connection parameters are incorrect or the data source name (DSN) is not properly formatted. To resolve this issue, double-check the database connection details such as the hostname, username, password, and database name in the DSN.

// Correcting the database connection parameters to resolve "invalid data source name" error
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'root';
$password = '';

try {
    $pdo = new PDO($dsn, $username, $password);
    echo "Connected successfully";
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}