修改
我已经上传了csv文件。但现在,我想更新上传的csv文件中的数据。如果csv数据已经存在于表中,我需要更新该数据,如果没有,我将作为新记录插入。这是我的代码
if(isset($_POST['import'])) { //import csv file into database
if(isset($_FILES['csv']['name'])) {
$file_type = explode('.',$_FILES['csv']['name']);
if($file_type[1]=="csv") {
$handle = fopen($_FILES['csv']['tmp_name'], "r");
$data = array();
while(($data=fgetcsv($handle,1000,",")) != FALSE ){
$id=$data[0];
$a = $data[1];
$b = $data[2];
$date = date('Y-m-d h:i:s',time());
$sql = "CREATE TEMPORARY TABLE temp_table LIKE question;
LOAD DATA INFILE '$file_name'
INTO TABLE temp_table
fields terminated by ','
optionally enclosed by ''
lines terminated by '\r\n'
(id, question, ans_number, a_one, a_two, a_three, a_four, a_five);
UPDATE question
INNER JOIN temp_table on temp_table.id = question.id
SET question.question = temp_table.question;
DROP TEMPORARY TABLE temp_table;";
mysql_db_query($dbname, $sql)or die(mysql_error());
$insert_id = mysql_insert_id();
echo "insert id: $insert_id<br/><br/>";
exit();
$count = 0;
for($j=2;$j<count($data);$j++) {
$b_name = $data[$j];
$count++;
if($count == $b) {
$is_answer = yes;
}else {
$is_answer = no;
}
if($b_name != "") {
***#I want to update and insert here***
$ans_sql = "INSERT INTO a_table(name,is_answer,id) VALUES('$b','$is_answer','$insert_id')";
mysql_db_query($dbname, $ans_sql);
}
}
}
fclose($handle);
}
}
}
但我每次都得到错误
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LOAD DATA INFILE 'Question.csv' INTO TABLE temp_table fields ter' at line 3
在我的csv文件中,我有这样的数据
id, question, ans_number, a_one, a_two, a_three, a_four, a_five
但是我想在问题表中添加问题,并附上相关的ID。 其他数据将添加到另一个表中。
我不确定我的语法有什么问题。怎么解决呢?