我有以下代码上传csv文件到mysql数据库。它工作得很好,但是如果csv文件包含每个列的标题,它将在表的第一行上传。我想删除csv文件的第一行,而得到存储在数据库中。我该怎么做呢?
<?php
//connect to the database
$connect = mysql_connect("localhost","root","");
mysql_select_db("crm",$connect); //select the table
//
if ($_FILES[csv][size] > 0) {
//get the csv file
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
mysql_query("INSERT INTO lead (name, lead_value, status) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."',
'".addslashes($data[2])."'
)
");
}
} while ($data = fgetcsv($handle,1000,",","'"));
//
//redirect
header('Location: import.php?success=1'); die;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Import a CSV File with PHP & MySQL</title>
</head>
<body>
<?php if (!empty($_GET[success])) { echo "<b>Your file has been imported.</b><br><br>"; } //generic success notice ?>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
Choose your file: <br />
<input name="csv" type="file" id="csv" />
<input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>
我正在使用的示例代码,它应该工作,因为我在生产环境中使用它
$handle = fopen("stuff.csv","r");
/* assuming that first row has collumns names */
$query = "INSERT INTO table(";
$cols = fgetcsv($handle,100000,';','"');
$query .= implode(", ",$cols).") VALUES";
$values = "";
/* cycle through each row and build mysql insert query */
while($data = fgetcsv($handle,100000,';','"')) {
$values .= " ( ";
foreach($data as $text) {
$values .= "'".$text."', ";
}
$values = substr($values,0,-2);
$values .= "), ";
}
/* remove last 2 chars */
$values = substr($values,0,-2);
$query .= $values;
echo $query;
fclose($handle);
注意这个脚本将返回mysql查询…
我认为您的意思是不希望将CSV数据的第一个行插入到表中。在这个假设下工作(注意,我不是PHP程序员,所以我所做的更改应该被视为伪代码):
if ($_FILES[csv][size] > 0) {
$first_time = true;
//get the csv file
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($first_time == true) {
$first_time = false;
continue;
}
if ($data[0]) {
mysql_query("INSERT INTO lead (name, lead_value, status) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."',
'".addslashes($data[2])."'
)
");
}
} while ($data = fgetcsv($handle,1000,",","'"));
//redirect
header('Location: import.php?success=1'); die;
}
如果我正确理解你,你想删除标题行吗?我会用LOAD DATA
代替INSERT INTO
LOAD DATA INFILE '/tmp/test.csv' INTO TABLE test FIELDS TERMINATED BY ',' IGNORE 1 LINES;
LOAD DATA在性能方面远远优于INSERT。