4

我现在正在导入我的 csv,除了一件事,我如何让导入忽略第一行中的数据?员工将上传与第一行中的列名相同的格式。

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
    $handle = fopen($_FILES['filename']['tmp_name'], "r");

    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $import = "INSERT into tictoc(employee,taskname,tasktime,sessiontime,sessionstart,sessionend,sessionnotes) values('" . $userinfo['first_name'] . " " . $userinfo['last_name'] . "','$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]')";

        mysql_query($import) or die(mysql_error());
    }

    fclose($handle);

    print "Import done";
}
4

8 回答 8

7

只需设置一个变量$i = 0 然后仅插入何时$i = 1或更多

if (isset($_POST['submit'])) {
    $i=0; //so we can skip first row

    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
    $handle = fopen($_FILES['filename']['tmp_name'], "r");

    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        if($i>0) {
            $import="INSERT into tictoc(employee,taskname,tasktime,sessiontime,sessionstart,sessionend,sessionnotes) values('".$userinfo['first_name']." ".$userinfo['last_name']."','$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]')";

            mysql_query($import) or die(mysql_error());
        }
        $i++;
    }

    fclose($handle);

    print "Import done";
}
于 2012-09-04T17:01:20.367 回答
6

您可以简单地使用 MySQL 的LOAD DATA INFILE命令,这比将 CSV 解析为 PHP、为每条记录构造一个语句、将其作为字符串提交给 MySQL 并让 MySQL 为 SQL 解析所述字符串(有 SQL 注入的风险)要快得多:INSERT

LOAD DATA INFILE ? INTO TABLE tictoc
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
IGNORE 1 LINES
(tasktime, sessiontime, sessionstart, sessionend, sessionnotes)
SET employee = ?, taskname = ?

使用 PDO:

$dbh = new PDO('mysql:dbname='.$dbname, $username, $password);

if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
  $qry = $dbh->prepare('
    LOAD DATA INFILE :filepath INTO TABLE tictoc
    FIELDS TERMINATED BY \',\' OPTIONALLY ENCLOSED BY \'"\'
    IGNORE 1 LINES
    (tasktime, sessiontime, sessionstart, sessionend, sessionnotes)
    SET employee = :employee, taskname = :taskname
  ');

  $qry->execute(array(
    ':filepath' => $_FILES['filename']['tmp_name'],
    ':employee' => $userinfo['first_name'],
    ':taskname' => $userinfo['last_name']
  ));
}
于 2012-09-04T17:50:19.577 回答
3

不需要变量。它比这简单得多。这是一个需要最少外部代码的解决方案,并且工作得很好。尝试放置:

$headers = fgetcsv($handle, 1000, ",");

在获取 CSV 数据的 while() 循环之前。这会抓住标题,但不会将它们插入数据库。一旦 while 循环开始,第一行已经返回,因此将它们排除在 mysql 插入之外。最重要的是,似乎需要标题,所以这也解决了这个问题。

所以最后,

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
    $handle = fopen($_FILES['filename']['tmp_name'], "r");

    //Grab the headers before doing insertion
    $headers = fgetcsv($handle, 1000, ",");

    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $import = "INSERT into tictoc(employee,taskname,tasktime,sessiontime,sessionstart,sessionend,sessionnotes) values('" . $userinfo['first_name'] . " " . $userinfo['last_name'] . "','$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]')";

        mysql_query($import) or die(mysql_error());
    }

    fclose($handle);

    print "Import done";
}
于 2012-09-05T00:30:49.863 回答
3

如果你喜欢,也许你可以使用这种方式:

$i=0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $i++;
    if($i==1) continue;

    $import="INSERT into tictoc(employee,taskname,tasktime,sessiontime,sessionstart,sessionend,sessionnotes) values('".$userinfo['first_name']." ".$userinfo['last_name']."','$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]')";

     mysql_query($import) or die(mysql_error());
}
于 2012-09-04T17:03:17.040 回答
2

我已经实现了这段代码,它是经过测试的代码。我认为这是非常充分的

您必须遵循一些规则:-

1.你的csv文件根据数据库表名(例如:db表名是users然后csv应该是users.csv)

2.您的 csv 文件的第一行应该是 db 表字段名称(例如:ID、名称等),然后开始您的数据输入

3.您可以从以下位置下载数据源类:- http://code.google.com/p/php-csv-parser/因为我在代码下面有要求:require_once 'CSV/DataSource.php';

<?php
ini_set('memory_limit','512M');
$dbhost = "localhost";
$dbname = "excel_import";
$dbuser = "root";
$dbpass = "";

$conn=mysql_connect ($dbhost, $dbuser, $dbpass) or die ("I cannot connect to the database because: " . mysql_error());
mysql_select_db($dbname) or die("Unable to select database because: " . mysql_error());


require_once 'CSV/DataSource.php';


$filename = "users.csv";
$ext = explode(".",$filename);
$path = "uploads/".$filename;

$dbtable = $ext[0];

import_csv($dbtable, $path);


function import_csv($dbtable, $csv_file_name_with_path)
{
    $csv = new File_CSV_DataSource;
    $csv->load($csv_file_name_with_path);

    $csvData = $csv->connect();

    $res='';
    foreach($csvData  as $key)
    {
        $myKey ='';
        $myVal='';
        foreach($key as $k=>$v)
        {
            $myKey .=$k.',';
            $myVal .="'".$v."',";
          }

        $myKey = substr($myKey, 0, -1);
        $myVal = substr($myVal, 0, -1); 
        $query="insert into ".$dbtable." ($myKey)values($myVal)";
        $res=  mysql_query($query);

    }

    if($res ==1)
    {

                echo "record successfully Import.";

    }else{

                echo "record not successfully Import.";
    }
}
于 2012-09-04T17:09:19.980 回答
2

你可以试试这个:

array_shift($data);
于 2012-09-04T17:01:28.310 回答
1

while在循环前声明一个变量

$row=1;

然后在while循环中放置这个条件

if($row==1){
   $row++; 
   continue;
}
于 2017-01-02T07:13:11.517 回答
0
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
$handle = fopen($_FILES['filename']['tmp_name'], "r");
fgetcsv($handle); //skip the reading of the first line from the csv file

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $import = "INSERT into tictoc(employee,taskname,tasktime,sessiontime,sessionstart,sessionend,sessionnotes) values('" . $userinfo['first_name'] . " " . $userinfo['last_name'] . "','$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]')";

    mysql_query($import) or die(mysql_error());
}

fclose($handle);

print "Import done";

}

于 2019-02-28T11:09:11.047 回答