我有一个包含 2 列(公司名称、客户名称)的 csv 文件。我在 tbl_company 中插入 company_name,在 tbl_customer 中插入 customer_name 和 company_id。所以 company_id 是 tbl_customer 中的外键。现在我面临的问题是我不想在我的 tbl_company 中插入公司名称超过 1 次。任何人都可以检查我写这个条件的代码。
我的 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');
}
最佳答案
这可能不是最好的方法,但你可以设计这样的东西:
$filename = $_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0) {
$file = fopen($filename, "r");
ini_set('max_execution_time', 300);
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) {
$company_name = $emapData[0];
// checking
// get ID from tbl_company and insert as foreign key in tbl_customer
$sql_LID = "SELECT * FROM tbl_company WHERE company_name = '$company_name'";
$res_LID = mysql_query($sql_LID);
if(mysql_num_rows($res_LID) <= 0) {
// if does not exist
// Insert company name into company table
$sql_comp = "INSERT into tbl_company(company_name) values ('$company_name')";
mysql_query($sql_comp);
$lastID = mysql_insert_id();
} else {
$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);
}
fclose($file);
echo 'CSV File has been successfully Imported';
header('Location: index.php');
}
关于php - 导入 CSV 数据时跳过重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26135965/