【发布时间】:2012-01-15 00:49:03
【问题描述】:
我正在使用以下脚本将记录上传到我的 MYSQL 数据库,我可以看到的问题是客户端记录是否已上传并且它已经存在于数据库中并且是重复的。
我在这里看到很多关于人们询问如何在上传时从 csv 文件本身中删除重复项的帖子,例如,如果 csv 中有两个名称 bob 和邮政编码 lh456gl 的实例不要上传它,但是什么我想知道是否可以在添加该记录之前先检查数据库中的记录,以免插入已经存在的记录。
类似:
if exist namecolumn=$name_being_inserted and postcode=postcode_being_inserted then
do not add that record.
这有可能吗?
<?php
//database connect info here
//check for file upload
if(isset($_FILES['csv_file']) && is_uploaded_file($_FILES['csv_file']['tmp_name'])){
//upload directory
$upload_dir = "./csv";
//create file name
$file_path = $upload_dir . $_FILES['csv_file']['name'];
//move uploaded file to upload dir
if (!move_uploaded_file($_FILES['csv_file']['tmp_name'], $file_path)) {
//error moving upload file
echo "Error moving file upload";
}
//open the csv file for reading
$handle = fopen($file_path, 'r');
while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
//Access field data in $data array ex.
$name = $data[0];
$postcode = $data[1];
//Use data to insert into db
$sql = sprintf("INSERT INTO test (name, postcode) VALUES ('%s','%s')",
mysql_real_escape_string($name),
mysql_real_escape_string($postcode)
);
mysql_query($sql) or (mysql_query("ROLLBACK") and die(mysql_error() . " - $sql"));
}
//delete csv file
unlink($file_path);
}
?>
【问题讨论】:
-
您应该在所有用于确定记录是否重复的列中添加唯一索引。这样 MySQL 就不会让你插入重复项。虽然它可能非常愚蠢,如果你想做任何智能的事情,你可能需要在插入之前运行一个选择,比如在地址组件中考虑错位的空格/标点符号
-
嗨,问题是这些数据来自预先存在的基于桌面的客户记录系统,客户端只是从中导出数据并导入,因此没有导入主键,只是客户管理软件中的字段。
-
不一定是PK,只要是唯一索引即可。两者不是同义词,也不是相互排斥的。