我有这个 php 代码,旨在将 csv 文件中的所有行和列作为记录导入 mysql 表。它成功地从 csv 插入到名为“import_items”的 mysql 表中,但是如果我重新导入,它将插入重复的记录。我只需要在哪里安装查询更新,它应该检查表名中的 IF ITEM EXISTS -> Update values , IF NOT EXISTS ..Insert record!
这是我的代码:
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
File to import:<br />
<input size='30' type='file' name='filename'>
<input type="submit" name="submit" value="Upload"></form>
<?php
require_once('connect_db.php');
//Upload File
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
//Import uploaded file to Database
$row = 1;
$handle = fopen($_FILES['filename']['tmp_name'], "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
//Update Database Values
$import="insert into import_items (item_no,qty,actual_price,discount_price,difference_price,date) VALUES('".mysql_real_escape_string($data[0])."', '".mysql_real_escape_string($data[1])."', '".mysql_real_escape_string($data[2])."', '".mysql_real_escape_string($data[3])."', '".mysql_real_escape_string($data[4])."', '".$date = date('Y-m-d')."')";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
}
}
?>
谢谢你