douquanjie9326
2017-04-28 11:13
浏览 41
已采纳

无法获取fgetcsv文件以使用MySQL数据库

I have tried to get this to fgetcsv function to output all rows of CSV file into my database. It seems quite standard functionality but it still doesn't work.

Here is my code I am trying to run:

<?php
$file = $_FILES['records_csv']['tmp_name'];
$handle = fopen($file,"r");

while(($csv = fgetcsv($handle,1000,",")) !== false) {
    $sql = "INSERT INTO records(artist, title, type, size, year, status)
    VALUES ('".$csv[0]."', '".$csv[1]."', '".$csv[2]."', '".$csv[3]."','".$csv[4]."','ACTIVE')"; 
}

if ($conn->query($sql) === TRUE) {
    echo "File uploaded successfully!";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}     

When I do run it, it only seems to enter the second line of the file into the database? I don't know why this is happening??

My CSV file looks like this:

The Jam,All Around The World,Single,7 inch,1977
The Jam,Strange Town,Single,7 inch,1979

And my form I am uploading from looks like this:

<form method="post" class="AddCSV_form" enctype="multipart/form-data">
    <input type="file" name="records_csv">
    <input type="submit" name="csv_sub" value="Upload">
</form>

Thanks.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douzhangshao6369 2017-04-28 11:19
    已采纳
    $file = $_FILES['records_csv']['tmp_name'];
    $handle = fopen($file,"r");
    $values = array();
    while(($csv = fgetcsv($handle,1000,",")) !== false)
    {
       $values[] = "('".$csv[0]."', '".$csv[1].
                   "', '".$csv[2]."','".$csv[3]."','".$csv[4]."','ACTIVE')"; 
    }
    $sql = "INSERT INTO records (artist, title, type, size, year, status) VALUES "
           . implode(',',$values); 
    
    if ($conn->query($sql) === TRUE) {
       echo "File(s) uploaded successfully!";
    } else {
       echo "Error: " . $sql . "<br>" . $conn->error;
    } 
    

    have a nice ...

    评论
    解决 无用
    打赏 举报
  • 查看更多回答(1条)

相关推荐 更多相似问题