1

我为用于导入 csv 文件的 PHP 创建了一个名为 import.php 的文件。但它不能正常工作。我在数据库中有 3 个字段。名称 id 电子邮件电子邮件的数值始终为 0,名称为空。

这是脚本的一部分。

任何想法为什么它会被读成一长串?

   <?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> 
4

1 回答 1

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);
?>
于 2013-10-07T08:11:02.827 回答