Running multiple queries with mysqli
Working on a currency conversion service, using Bloomberg to get live rates of currencies (using USD as base rate). I can get all of the rates from bloomberg no problem, just when inserting them into the database (for cache and retrieving later) it spits out the error
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in
.
Here is my PHP for the specific part:
//Select all the currency codes where the rate has not been set
$q = "SELECT currency_code FROM `currency` WHERE rate = 0";
//Run the query
$r = mysqli_query($dbc,$q);
//If the query was successful..
if($r){
//Fetch the results from the query
while($row = mysqli_fetch_array($r, MYSQLI_ASSOC)){
//Set $curr to the currency code
$curr = $row['currency_code'];
//Set $rate to a currency_code from the previous query, and put it in the bloomberg function
$rate = bloomberg($curr);
//Update the currency table with the vars just set
$q = "UPDATE currency SET rate='$rate' WHERE currency_code='$curr'";
//Run the query
$r = mysqli_query($dbc, $q);
}
When I run this, it updates only one item in the database on each refresh, which means the while is failing somewhere, but I can't seem to pinpoint where.
For solving this I have searched Google for a good twenty minutes, and read about myqli not being able to run multiple queries. This is the way I've been taught via PHP books to run querys and fetch them using PHP and mySQL.
Here is the bloomberg function by the way: uwe_get_file = function to get around Uni's proxy service
function bloomberg($to){
$cur = $to;
$file = uwe_get_file('http://www.bloomberg.com/personal-finance/calculators/currency-converter/');
if(preg_match ("/p开发者_JAVA技巧rice\['$cur:\S*\s=\s(\S*);/",$file,$out)){
return number_format($out[1], 4);
}
}
Links to additional reading/explanation/help welcome.
Your are overwriting $r
with the result of an UPDATE statement:
$q = "UPDATE currency SET rate='$rate' WHERE currency_code='$curr'";
$r = mysqli_query($dbc, $q);
mysqli_query('UPDATE...')
will not return a mysqli_result
object. Therefore, at the second pass of your while
, $r
has been changed to a boolean value. Change it to a different variable name to fix it:
$q = "UPDATE currency SET rate='$rate' WHERE currency_code='$curr'";
$u = mysqli_query($dbc, $q);
精彩评论