What are the advantages of using mysqli or PDO over the traditional mysql functions in PHP?

Using mysqli or PDO over the traditional mysql functions in PHP provides several advantages such as improved security through prepared statements, support for multiple database types, and better error handling capabilities. Additionally, both mysqli and PDO offer object-oriented interfaces which can make code more readable and maintainable.

// Using PDO to connect to a MySQL database
$host = 'localhost';
$dbname = 'my_database';
$username = 'my_username';
$password = 'my_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();
}