【发布时间】:2017-04-07 12:38:42
【问题描述】:
我想通过 csv 文件将数据添加到数据库。我能够做到这一点,但是每当我再次上传该文件时,它就会重复,我不希望特定行的数据再次连续输入,但特定列字段可能会重复。以下代码用于上传文件具有表位置的数据库,其中包含 ID(自动递增)、州、市的字段。
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
require ('dbconfig.php');
if(isset($_POST['submit']))
{
$fname = $_FILES['sel_file']['name'];
echo 'upload file name: '.$fname.' ';
$chk_ext = explode(".",$fname);
if(strtolower(end($chk_ext)) == "csv")
{
$filename = $_FILES['sel_file']['tmp_name'];
$handle = fopen($filename,"r");
while (($data = fgetcsv($handle, 10000, ",")) !== FALSE)
{
$sql = "INSERT into location(State,City,District) values('$data[0]','$data[1]','$data[2]')";
mysqli_query($conn,$sql) or die ;
}
fclose($handle);
echo "Successfully imported";
}
else
{
echo "Invalid File";
}
}
?>
<h1>import CSV file</h1>
<form action='<?php echo $_SERVER["PHP_SELF"];?>' method='post' enctype="multipart/form-data">
Import File: <input type='file' name='sel_file' size='20'>
<input type='submit' name='submit' value='submit'>
</form>
【问题讨论】:
-
使用 insert ignore into(........) 得到解决方案,同时使城市在表中独一无二