我有以下代码将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>
答案 0 :(得分:2)
我正在使用的示例代码,它应该可以工作,因为我在生产环境中使用它
$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查询...不执行它,因此请根据需要进行更改。
答案 1 :(得分:1)
我认为您的意思是您不希望将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;
}
答案 2 :(得分:1)
如果我理解正确你想要删除标题行?我会使用LOAD DATA
代替INSERT INTO
LOAD DATA INFILE '/tmp/test.csv' INTO TABLE test FIELDS TERMINATED BY ',' IGNORE 1 LINES;
LOAD DATA在性能方面远优于INSERT。