gpt4 book ai didi

php - 使用 PHP 将 CSV 文件导入 MySQL

转载 作者:行者123 更新时间:2023-11-29 02:19:51 24 4
gpt4 key购买 nike

我正在编写一个 PHP 脚本,用于从大量客户导入 CSV 数据。数据有 12 行和 10 列(见下文)。当我使用 phpMyAdmin 的 MySQL 导入时,没有问题(所有 12 行导入都很好!)但是,当我尝试使用 PHP 脚本导入时,它只导入第一行或最后一行。我用谷歌搜索了许多不同的方法来编写相同的脚本,但都无济于事。目标是让用户能够自动将 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,March,NULL,NULL,NULL,NULL,NULL,NULL,NULL,3 1,April,NULL,NULL,NULL,NULL,NULL,NULL,NULL,4 1,May,NULL,NULL,NULL,NULL,NULL,NULL,NULL,5 1,June,NULL,NULL,NULL,NULL,NULL,NULL,NULL,6 1,July,NULL,NULL,NULL,NULL,NULL,NULL,NULL,7 1,August,NULL,NULL,NULL,NULL,NULL,NULL,NULL,8 1,September,NULL,NULL,NULL,NULL,NULL,NULL,NULL,9 1,October,NULL,NULL,NULL,NULL,NULL,NULL,NULL,10 1,November,NULL,NULL,NULL,NULL,NULL,NULL,NULL,11 1,December,NULL,NULL,NULL,NULL,NULL,NULL,NULL,12

最佳答案

这对我来说很好 -

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);
}

}

关于php - 使用 PHP 将 CSV 文件导入 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33663775/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com