我正在使用以下代码将 csv 导入 mysql。
if($_POST['sform'] == "1")
{
$fname = $_FILES['upload']['name'];
$chk_ext = explode(".",$fname);
if(strtolower($chk_ext[1]) == "csv")
{
$filename = $_FILES['upload']['tmp_name'];
$row = 1;
if (($handle = fopen($filename, "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$row++;
$data_entries[] = $data ;
}
fclose($handle);
}
foreach($data_entries as $line)
{
$sql = "INSERT into testposts(ID,UID,title,tags,desc) values('','$data[0]','$data[1]','$data[2]','$data[3]')";
$conn->execute($sql);
$conn->execute($line);
}
$msg = "Successfully Imported";
}
else
{
$error = "Invalid File";
}
}
当我尝试更新时,所有值都会更新为 0
我的 csv 文件如下(示例)
1,title,tags,send2
不包括 PID 值,因为它是自动递增的
所以我尝试了我的第二个变体
if($_POST['sform'] == "1")
{
$fname = $_FILES['upload']['name'];
$chk_ext = explode(".",$fname);
if(strtolower($chk_ext[1]) == "csv")
{
$filename = $_FILES['upload']['tmp_name'];
$handle = fopen($filename, "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$sql = "INSERT into testposts(ID,UID,title,tags,desc) values('','$data[0]','$data[1]','$data[2]','$data[3]')";
mysql_query($sql) or die(mysql_error());
//$conn->execute($sql);
}
$msg = "Successfully Imported";
}
else
{
$error = "Invalid File";
}
}
在我的第二个代码中,它按预期正确上传了值,但它插入了两次。
任何帮助将不胜感激,谢谢