我正在编写一个PHP脚本,用于从无数客户导入CSV数据。数据有12行10列(见下文)。当我使用phpMyAdmin的MySQL Import时,没有问题(所有12行导入都很好!)但是,当我尝试使用PHP脚本导入时,它只导入第一行或最后一行。我用Google搜索了许多不同的方法来编写相同的脚本无济于事。目标是让用户能够自动将CSV上传到表格中。
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) {
mysql_query("INSERT INTO summary_td (customer_id, month, Income, Savings, Revolving_Expenses, Utilities, Services, Luxuries, Charities, month_id) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."',
'".addslashes($data[2])."',
'".addslashes($data[3])."',
'".addslashes($data[4])."',
'".addslashes($data[5])."',
'".addslashes($data[6])."',
'".addslashes($data[7])."',
'".addslashes($data[8])."',
'".addslashes($data[9])."'
)
");
}
} while ($data = fgetcsv($handle,1000,",","'"));
//redirect
header('Location: import.php?success=1'); die;
}
?>
CSV数据:
1,January,5000,899,899,899,899,899,899,1 1,February,NULL,NULL,NULL,NULL,NULL,NULL,NULL,2 1,三月,NULL,NULL,NULL,NULL,NULL,NULL,NULL,3 1,四月,NULL,NULL,NULL,NULL,NULL,NULL,NULL,4 1,5月5日,NULL,NULL,NULL,NULL,NULL,NULL,NULL, 1,六月,NULL,NULL,NULL,NULL,NULL,NULL,NULL,6 1,七月,NULL,NULL,NULL,NULL,NULL,NULL,NULL,7 1,八月,NULL,NULL,NULL,NULL,NULL,NULL,NULL,8 1,九月,NULL,NULL,NULL,NULL,NULL,NULL,NULL,9 1,十月,NULL,NULL,NULL,NULL,NULL,NULL,NULL,10 1,十一月,NULL,NULL,NULL,NULL,NULL,NULL,NULL,11 1,腊,NULL,NULL,NULL,NULL,NULL,NULL,NULL,12
答案 0 :(得分:2)
这对我来说很好 -
function upload(){
ini_set('auto_detect_line_endings',TRUE);
if (($handle = fopen($_FILES['userfile']['tmp_name'], "r")) !== FALSE) {
$firstRow = true;
while (($data = fgetcsv($handle, 4096, ",",'"')) !== FALSE)
{
$num = count($data);
$data1 = array(
'name' => $data[0],
'nric' => $data[1],
'email' => $data[2],
'address' => $data[3] ,
'postal' => $data[4],
'mobile_country_code' => $data[5],
'mobile' => $data[6],
'gender' => $data[7],
'country' => $data[8],
'nationality' => $data[9],
'dob' => $dob,
'notes' => $data[11],
'newsletter' => $data[12],
'delete' => $data[13]
);
//echo "<pre/>";print_r($data) ;exit();
$this->db->insert('members', $data1);
$member_id = $this->db->insert_id();
}
//echo "<pre/>";print_r($data) ;exit();
fclose($handle);
}
ini_set('auto_detect_line_endings',FALSE);
}
}