I would like to update a MySQL table containing up-to-date currency symbol & value pairs from a given exchange rates service once every 24 hours.
Right now, I do something like this:
foreach ($currencies->rates as $currency => $rate) {
$connection->addQuery("update/{$currency}", "UPDATE `i18n/currencies` SET `rate` = ? WHERE `code` = ?;", $rate, $currency);
}
$connection->output();
I get the $currencies
object out from a JSON-encoded response, $connection
is a reference to my database connection class.
If I want to create a SQL query group (a class I created to perform bulk commands), the syntax would be like this:
if (!empty($this->attributes["queries"])) {
$queries = implode(" ", array_map(function ($input) { return (mb_strpos($input->attributes["query"], ";") !== false ? $input->attributes["query"] : "{$input->attributes["query"]};"); }, $this->attributes["queries"]));
$parameters = [];
foreach ($this->attributes["queries"] as $query) {
if (!empty($query->attributes["parameters"])) {
$parameters = array_merge($parameters, $query->attributes["parameters"]);
}
}
}
This way, if I have the following set of queries (with their final values after the query):
UPDATE `i18n/currencies` SET `rate` = ? WHERE `code` = ?; [1.7, AED]
UPDATE `i18n/currencies` SET `rate` = ? WHERE `code` = ?; [2.1, BYR]
UPDATE `i18n/currencies` SET `rate` = ? WHERE `code` = ?; [0.7, EUR]
UPDATE `i18n/currencies` SET `rate` = ? WHERE `code` = ?; [1.1, GBP]
The final string would be like this:
UPDATE `i18n/currencies` SET `rate` = ? WHERE `code` = ?; UPDATE `i18n/currencies` SET `rate` = ? WHERE `code` = ?; UPDATE `i18n/currencies` SET `rate` = ? WHERE `code` = ?; UPDATE `i18n/currencies` SET `rate` = ? WHERE `code` = ?; [1.7, AED, 2.1, BYR, 0.7, EUR, 1.1, GBP]
The query is prepared and executed like this:
if ($output = $this->attributes["references"]["parent"]->attributes["link"]->prepare($queries, [\PDO::ATTR_CURSOR => \PDO::CURSOR_FWDONLY])) {
$result = ($output->execute((!empty($parameters) ? $parameters : null)) ? true : false);
}
But it's not working. I've tried different modifications to my code, but none of them seems to provide me with the solution I'm looking for.
Is it really possible to do BULK updates with PDO passing the parameters like this? Or is it another way I haven't discovered yet? Maybe it's not doable at all and I'm just being stubborn. I could rewrite this update script with single SQL queries, as my connection class will fire them up, from the first to the last one.
Can you give me a hint?