What are the key differences between using the mysql_ functions and newer alternatives like PDO or mysqli_ in PHP?

When working with databases in PHP, it is recommended to use newer alternatives like PDO or mysqli_ functions instead of the older mysql_ functions. This is because mysql_ functions are deprecated and no longer maintained, making them less secure and more prone to vulnerabilities. PDO and mysqli_ offer more features, better performance, and support for prepared statements, which help prevent SQL injection attacks.

// Using PDO to connect to a MySQL database
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'root';
$password = '';

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