导入到phpmysqladmin时从csv文件中获取特定行

时间:2015-12-23 20:38:22

标签: php sql

我是新来的,我试图获取日历csv文件的特定行并导入phpmysql数据库,但实际上无法获取它,希望有人可以帮我

this is my csv file

this is my database look like, i want to get row 4,6,8...so on from csv file and import to table:calendar, column:day and get row 3,5,7...to the same table but column:date

这是我的代码

<?php

include "dbFunctions.php"; //Connect to Database

$deleterecords = "TRUNCATE TABLE calendar"; //empty the table of its current records
mysqli_query($link, $deleterecords);

//Upload File

if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
    echo "<h1>" . "File ". $_FILES['filename']['name'] ." Uploaded Successfully." . "</h1>";
    echo "<h2>Displaying contents:</h2>";
    readfile($_FILES['filename']['tmp_name']);
}

//Import uploaded file to Database
    //exclude the first row title
    $row = 1;
if(($handle = fopen($_FILES['filename']['tmp_name'], "r")) !== FALSE){
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($i=0; $i<=38; $i++){
if($firstRow) { $firstRow = false; }
        else {
    $import="INSERT into class(day, date) 
                values('$data[0]','$data[1]')";

    mysqli_query($link, $import) or die(mysqli_error($link));

}

    echo $data[$i] . "<br />\n";
    }}

fclose($handle);

    }


//view upload form
    }else {

print "Upload csv file and clicking on Upload<br />\n";

print "<form enctype='multipart/form-data' action='uploadCalendar.php' method='post'>";

print "csv File to import:<br />\n";

print "<input size='50' type='file' name='filename'><br />\n";

print "<input type='submit' name='submit' value='Upload'></form>";


    }

&GT;

1 个答案:

答案 0 :(得分:0)

由于图案是奇数和偶数行。

$row = 0;
$i = 0;

$container = array();
if(($handle = fopen($_FILES['filename']['tmp_name'], "r")) !== FALSE){

    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

        if ($row > 2) {               

            if ($row % 2 == 0) {
                $i = $i - 6;
                $v = 'day';

            } else {
                $v = 'date';
            }

            foreach ($data as $column) {
                $container[$i][$v] = $column;
                $i++;
            }
        }                        
        $row++;
    }

fclose($handle);

}

foreach ($container as $value) {
     $import="INSERT into class(day, date) 
            values('".$value['day']."','".$value['date']."')";

    mysqli_query($link, $import) or die(mysqli_error($link));
}

$container应包含与当天配对的日期。像,

$container = [['day' => 'W1D1', 'date' => '19-Oct'], ['day' => 'W1D2', 'date' => '20-Oct']];

您可以使用循环插入数据库。