What are the benefits of using PDO or mysqli over the deprecated mysql functions for database queries in PHP?

The deprecated mysql functions in PHP are no longer recommended for database queries due to security vulnerabilities and lack of support. It is recommended to use either PDO (PHP Data Objects) or mysqli (MySQL Improved) for database operations as they provide more secure and flexible options for interacting with databases.

// Using PDO for database queries
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';

try {
    $pdo = new PDO($dsn, $username, $password);
    $stmt = $pdo->query('SELECT * FROM mytable');
    while ($row = $stmt->fetch()) {
        // process data
    }
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}