我有一個csv文件與列(公司名稱,客戶名稱)。我在tbl_company中插入company_name,在tbl_customer中插入customer_name和company_id。所以company_id是tbl_customer中的外鍵。現在我面臨的問題是我不想在我的tbl_company中多次插入公司名稱。任何人都可以檢查我寫這個條件的代碼。導入CSV數據時跳過重複值
我的PHP代碼
$filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
$x = 0;
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
ini_set('max_execution_time', 300);
if($x > 0) {
// Insert company name into company table
$sql_comp = "INSERT into tbl_company(company_name) values ('$emapData[0]')";
mysql_query($sql_comp);
//$lastID = mysql_insert_id();
// get last ID from tbl_company and insert as foreign key in tbl_customer
$sql_LID = "SELECT * FROM tbl_company ORDER BY id DESC";
$res_LID = mysql_query($sql_LID);
$row_LID = mysql_fetch_array($res_LID);
$lastID = $row_LID['id'];
// insert company id and customer name into table customer
$sql_cust = "INSERT into tbl_customer(comp_id,customer_name) values ('$lastID', '$emapData[1]')";
mysql_query($sql_cust);
}
$x++;
}
fclose($file);
echo 'CSV File has been successfully Imported';
header('Location: index.php');
}
問題可能更適合http://codereview.stackexchange.com – 2014-10-01 07:16:39