How can one effectively maintain currency exchange rates in PHP?
To effectively maintain currency exchange rates in PHP, one can utilize an API that provides real-time exchange rate data and store this data in a database for easy access and retrieval. By regularly updating the exchange rates in the database, one can ensure that the rates remain accurate and up-to-date for use in currency conversion calculations.
// Example code snippet to fetch exchange rates from an API and store them in a database
// Fetch exchange rates from API
$api_url = 'https://api.exchangeratesapi.io/latest';
$data = file_get_contents($api_url);
$rates = json_decode($data, true)['rates'];
// Store exchange rates in database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "exchange_rates";
$conn = new mysqli($servername, $username, $password, $dbname);
foreach ($rates as $currency => $rate) {
$sql = "INSERT INTO rates (currency, rate) VALUES ('$currency', $rate)";
$conn->query($sql);
}
$conn->close();
Related Questions
- Can PHP frameworks or libraries be utilized to streamline the process of creating a search form for user input?
- What security measures should be considered when implementing age verification using PHP and ID numbers?
- Is using the Modulo operator a more efficient way to extract the last digit of a number in PHP compared to converting it to a string?