What are the recommended approaches for handling database connections in PHP when interacting with MySQL?

When interacting with MySQL in PHP, it is recommended to use the PDO (PHP Data Objects) extension for handling database connections. PDO provides a consistent interface for accessing different database systems and offers features like prepared statements to prevent SQL injection attacks. By using PDO, you can ensure secure and efficient database interactions in your PHP applications.

// Establishing a connection to MySQL using PDO
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';

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