How can one properly establish a database connection in PHP to ensure successful data transfer?

To properly establish a database connection in PHP, you should use the PDO (PHP Data Objects) extension, which provides a flexible and secure way to access databases. By using PDO, you can connect to various database systems like MySQL, PostgreSQL, SQLite, etc. To ensure successful data transfer, make sure to handle any potential errors that may occur during the connection process.

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

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();
}
?>