What is the recommended method for querying data from a MySQL database using PHP?

When querying data from a MySQL database using PHP, it is recommended to use the PDO (PHP Data Objects) extension for improved security and flexibility. PDO provides a consistent interface for accessing different types of databases, including MySQL, and supports prepared statements to prevent SQL injection attacks. To query data from a MySQL database using PDO in PHP, you can use the following code snippet:

<?php
$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);

    $stmt = $pdo->prepare('SELECT * FROM mytable');
    $stmt->execute();

    while ($row = $stmt->fetch()) {
        // Process each row
    }
} catch (PDOException $e) {
    echo 'Error: ' . $e->getMessage();
}
?>