SQL在FOR循环中执行两次

时间:2013-05-08 12:01:00

标签: php mysql for-loop while-loop duplicates

我想我需要第二双眼睛。对于我的生活,我无法弄清楚为什么我的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);
}

2 个答案:

答案 0 :(得分:0)

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

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);
}

如果有更好的方法,我仍然很好奇。

答案 1 :(得分:0)

我看起来你正在使用一些代码迭代你的列,但实际上只有两个,包含sku和prod($ data [0]和$ data [1]。)如果是这样,那么你里面不需要for循环。 (顺便说一句,正是这个循环导致查询被执行两次,因为查询在其中。)看起来你还有两个计数器用于行(current_row和row),因此可以将它们组合起来。如果你使用if($ currentRow == 1 ...语句忽略第0行的标题,然后只处理2行,你会想要在准备好时将它切换到if($ currentRow&gt; 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);
}