Why is it recommended to use PDO instead of mysql_* functions in PHP for database interactions?

Using PDO instead of mysql_* functions in PHP is recommended because mysql_* functions are deprecated and no longer maintained. PDO provides a more secure and flexible way to interact with databases, with support for multiple database drivers and prepared statements to prevent SQL injection attacks.

// Using PDO to connect to a MySQL database
$host = 'localhost';
$dbname = 'database_name';
$username = 'username';
$password = 'password';

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