循环mysql表并从api抓取中更新内容

时间:2018-06-20 12:26:07

标签: php mysql arrays

我想每10-15分钟运行一个php脚本作为crontab并更新mysql表中的特定列。它从单个API值中提取并返回并更新单元格。我觉得我目前的解决方法是...但是随着桌子的增加,速度会变慢...有更好的方法吗?

$result = mysqli_query($con,"SELECT address,api_getbalance FROM product_log");

while($row = mysqli_fetch_array($result)) {
        $url = $row['api_getbalance']
        $address = $row['address']
        $newbalance = file_get_contents($url . '' . $address);
        $sql = "UPDATE product_log SET balance = ? WHERE address = ?";
        $Update = mysqli_prepare($con, $sql);
        if($Update) {
             mysqli_stmt_bind_param($Update, 'ss', $newbalance, $address); 
             mysqli_stmt_execute($Update);
        } else {
             echo 'Data Not Updated';
             error_log(mysqli_stmt_error($sUpdate));
        }
}
mysqli_close($con);

1 个答案:

答案 0 :(得分:3)

prepare语句应该处于循环外,它只需初始化一次,然后在循环内绑定参数并执行。更新的代码如下:

$result = mysqli_query($con, "SELECT address,api_getbalance FROM product_log");
$sql = "UPDATE product_log SET balance = ? WHERE address = ?";
$Update = mysqli_prepare($con, $sql);

while ($row = mysqli_fetch_array($result)) {
    $url = $row['api_getbalance'];
    $address = $row['address'];
    $newbalance = file_get_contents($url . '' . $address);
    if ($Update) {
        mysqli_stmt_bind_param($Update, 'ss', $newbalance, $address);
        mysqli_stmt_execute($Update);
    } else {
        echo 'Data Not Updated';
        error_log(mysqli_stmt_error($sUpdate));
    }
}
mysqli_close($con);