简体   繁体   English

而使用fgetcsv的Loop仅在第一个实例上更新MySQL数据库

[英]While Loop using fgetcsv only updating MySQL Database on first instance

I'm pulling a CSV file into a script, parsing it and then updating my MySQL table. 我正在将CSV文件拉入脚本中,对其进行解析,然后更新我的MySQL表。 The problem is that it's only inserting the data from the second row of the CSV file (first row is being skipped because it's the headers of the columns). 问题在于,它只是从CSV文件的第二行插入数据(第一行被跳过,因为它是列的标题)。 Here's my code: 这是我的代码:

$f = fopen("sample.csv", "r");
while(($line = fgetcsv($f)) !== FALSE){
    $time = $line[0];

    //SKIP FIRST LINE (WITH HEADERS)
    if($time == "Time"){
        continue;
    }
    else{
        $size = $line[1];
        $location = $line[2];
        $county = $line[3];
        $state = $line[4];
        $lat = $line[5];
        $lon = $line[6];
        $comments = $line[7];
        $sql = "INSERT INTO sample (time, size, location, county, state, lat, lon, comments) VALUES ('$time', '$size', '$location', '$county', '$state', '$lat', '$lon', '$comments')";
        $result = $mysqli->query($sql);
        //CHECK TO SEE IF THE LOOP IS WORKING THROUGH ALL DATA
        echo $size;
    }
}
fclose($f);

The issue is that it skips the first row successfully and then on the second loop through, it successfully updates the database. 问题是它成功跳过了第一行,然后在第二个循环中成功地更新了数据库。 As you can see, I've echo'ed out the value of $size and it echoes all the values of all the rows meaning it's looping through all the data correctly. 如您所见,我已经回显了$ size的值,并且它回显了所有行的所有值,这意味着它正确地循环了所有数据。 I'm not sure why it's not adding that data into each subsequent row. 我不确定为什么不将数据添加到随后的每一行中。

Thanks for your help! 谢谢你的帮助!

您需要将文本与文件分开,请尝试以下操作:

while(($line = fgetcsv($f,4096,",", '"')) !== FALSE){

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM