PHP CSVImport数据

时间:2013-10-07 07:42:08

标签: php

我为PHP创建了一个名为import.php的文件,用于导入csv文件。但它没有正常工作。我在database.name id电子邮件中有3个字段得到了alwyas数值0和名称为null。

这是脚本的一部分。

任何想法为什么它会被读作长线?

   <?php

    $connect = mysql_connect('localhost','root','');
    if (!$connect) {
    die('Could not <span class="IL_AD" id="IL_AD3">connect to</span> <span class="IL_AD" id="IL_AD12">MySQL</span>: ' . mysql_error());
    }

    $cid =mysql_select_db('test',$connect);
    // supply your database name

    define('CSV_PATH','D:/xampp/htdocs/import/');
    // path where your CSV file is located

    $csv_file = CSV_PATH . "aa.csv"; // Name of your CSV file
    $csvfile = fopen($csv_file, 'r');
    $theData = fgets($csvfile);
    $i = 0; while (!feof($csvfile)) {
    $csv_data[] = fgets($csvfile, 1024);
    $csv_array = explode(",", $csv_data[$i]);
  $insert_csv = array();
    $insert_csv['ID'] = $csv_array[0];
    $insert_csv['name'] = $csv_array[1];
    $insert_csv['email'] = $csv_array[2];
    $query = "INSERT INTO csv(ID,name,email)
    VALUES('','".$insert_csv['name']."','".$insert_csv['email']."')";
    $n=mysql_query($query, $connect );
    $i++;
    }
    fclose($csvfile);    
    echo "File data successfully imported to database!!";
    mysql_close($connect);
    ?>




and this is my input file from where i upload csv file....i got Warning msg and my data base fiel id is created and email value i got 0 and name id null.



<html>
<body>

<form action="impt.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>

</body>
</html> 

1 个答案:

答案 0 :(得分:0)

这是您使用fgetcsv

的代码
<?php

    $connect = mysql_connect('localhost','root','');

    if (!$connect) {
        die('Could not <span class="IL_AD" id="IL_AD3">connect to</span> <span class="IL_AD" id="IL_AD12">MySQL</span>: ' . mysql_error());
    }

    $cid = mysql_select_db('test', $connect);
    // supply your database name

    define('CSV_PATH','D:/xampp/htdocs/import/');
    // path where your CSV file is located

    $csv_file = CSV_PATH . "aa.csv"; // Name of your CSV file
    $csvfile = fopen($csv_file, 'r');

    $i = 0;
    while (($data = fgetcsv($csvfile, 1000)) !== FALSE) {
        if ($data != null) { // skip empty lines
            $insert_csv = array();
            $insert_csv['ID'] = $data[0];
            $insert_csv['name'] = $data[1];
            $insert_csv['email'] = $data[2];
            $query = "INSERT INTO csv(ID,name,email)
                      VALUES('','".$insert_csv['name']."','".$insert_csv['email']."')";
            $n=mysql_query($query, $connect );
        }
        $i++;
    }

    fclose($csvfile);    
    echo "File data successfully imported to database!!";
    mysql_close($connect);
?>