SQL在FOR循环中被执行两次


SQL being executed twice in FOR loop

我想我需要另一双眼睛。对于我的生活,我不能弄清楚为什么我的SQL INSERT查询每次迭代运行两次:

if (($handle = fopen($spreadsheet_url, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    if ($current_row == 1 || $current_row == 2) {
        $num = count($data);
        //echo "<p> $num fields in line $row: <br /></p>'n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            //echo $data[$c] . "<br />'n";
            try {
                set_time_limit(0);
                $stmt = $db_temp_kalio->prepare('INSERT INTO invupdate (sku,prod) VALUES(:sku, :prod)');
                $stmt->execute(array(':sku'=> $data[0], ':prod'=> $data[1])); }
            catch(PDOException $e) {
                echo 'ERROR: ' . $e->getMessage();
                exit; }
            }
        }
    $current_row++;
    }
fclose($handle);
}

嗯,我可能应该在寻求帮助之前多付出一点努力。我能够通过在循环中添加行重置计数器来解决这个问题:

if (($handle = fopen($spreadsheet_url, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    if ($current_row == 1 || $current_row == 2) {
        $row_reset = 0;
        $num = count($data);
        //echo "<p> $num fields in line $row: <br /></p>'n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            //echo $data[$c] . "<br />'n";
            if ($row_reset == 0) {
                try {
                    set_time_limit(0);
                    $stmt = $db_temp_kalio->prepare('INSERT INTO invupdate (sku,prod) VALUES(:sku, :prod)');
                    $stmt->execute(array(':sku'=> $data[0], ':prod'=> $data[1])); }
                catch(PDOException $e) {
                    echo 'ERROR: ' . $e->getMessage();
                    exit; }
                }
            $row_reset++;
            }
        }
    $current_row++;
    }
fclose($handle);
}

我还是很好奇是否有更好的方法

I看起来像是使用了一些代码来遍历列,但实际上只有两个,包含sku和prod ($data[0]和$data[1])。如果是这种情况,那么就不需要在里面使用for循环。(顺便说一句,正是这个循环导致查询被执行两次,因为查询在其中。)它看起来还像有两个计数器(current_row和row),因此它们可以组合在一起。如果您正在使用If ($currentRow == 1…语句忽略第0行的标题,然后只处理2行,当您准备运行整个电子表格时,您将需要将其切换为if ($currentRow> 0)。在catch子句中使用break而不是exit将导致代码退出while循环并击中fclose语句:

if (($handle = fopen($spreadsheet_url, "r")) !== FALSE) {
$currentRow = 0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    if ($currentRow == 1 || $currentRow == 2) {
        $num = count($data);
        //echo "<p> $num fields in line $currentRow: <br /></p>'n";
        //echo "<p> The data for this row is: " . $data[0]  . " " . $data[1] . "'n";
        try {
            set_time_limit(0);
            $stmt = $db_temp_kalio->prepare('INSERT INTO invupdate (sku,prod) VALUES(:sku, :prod)');
            $stmt->execute(array(':sku'=> $data[0], ':prod'=> $data[1]));
        }
        catch(PDOException $e) {
            echo 'ERROR: ' . $e->getMessage();
            break;
        }
    }
    $currentRow++;
}
fclose($handle);
}