How can PHP be used to insert retrieved currency exchange rates into a database?

To insert retrieved currency exchange rates into a database using PHP, you can first fetch the rates from an API, then establish a connection to your database using PDO or mysqli, and finally insert the rates into a table in your database.

// Fetch currency exchange rates from an API
$rates = file_get_contents('https://api.exchangerate-api.com/v4/latest/USD');
$rates = json_decode($rates, true);

// Establish a connection to the database
$dsn = 'mysql:host=localhost;dbname=your_database';
$username = 'your_username';
$password = 'your_password';
$db = new PDO($dsn, $username, $password);

// Insert rates into a table in the database
$stmt = $db->prepare("INSERT INTO exchange_rates (currency, rate) VALUES (:currency, :rate)");
foreach($rates['rates'] as $currency => $rate) {
    $stmt->execute(array(':currency' => $currency, ':rate' => $rate));
}