2014-01-20 125 views
2

我有以下負載數據infile的查詢:LOAD DATA INFILE - 場TERMINATED錯誤

LOAD DATA INFILE $csv INTO TABLE safety_quiz FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n' (first_name, last_name, person_id, quiz_result) 

這將產生以下的錯誤:

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 '../import/import_20_01_2014.csv INTO TABLE safety_quiz FIELDS TERMINATED BY ',' ' at line 1

CSV格式是:

Bob,Smith,123456789,100 
Fred,Jones,987654321,100 

表結構爲:

CREATE TABLE `safety_quiz` (
    `safety_quiz_pk` int(8) NOT NULL AUTO_INCREMENT, 
    `first_name` varchar(80) NOT NULL, 
    `last_name` varchar(80) NOT NULL, 
    `person_id` varchar(9) NOT NULL, 
    `quiz_result` varchar(10) NOT NULL, 
    PRIMARY KEY (`safety_quiz_pk`) 
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; 

我看過對同一問題的其他計算器的問題,但我不能看到那裏的錯誤是...

UPDATE

全碼:

if(isset($_POST['submit'])){ 

if(!empty($_FILES["file"]["tmp_name"])){ 

$type = explode(".",$_FILES['file']['name']); 

if(strtolower(end($type)) == 'csv'){ 

$path = '../import/'; 
$file_name = 'import_' . date('d_m_Y') . '.csv'; 
move_uploaded_file($_FILES["file"]["tmp_name"], $path . $file_name); 

} else { 
    $message = 'Only csv files can be uploaded.'; 
} 
} else { 
    $message = 'You need to attach a csv file.';  

} 

$csv = $path . $file_name; 

$query = "LOAD DATA INFILE '$csv' INTO TABLE safety_quiz FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n' (first_name, last_name, person_id, quiz_result)"; 
$result = mysql_query($query, $connection) or die(mysql_error()); 
} 

工作代碼

看起來像csv的路徑需要是abs olute(不知道爲什麼...),但這個工程:

$csv = '/var/www/html/labs/import/' . $file_name; 

$query = "LOAD DATA INFILE '$csv' INTO TABLE safety_quiz FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (first_name, last_name, person_id, quiz_result)"; 
$result = mysql_query($query, $connection) or die(mysql_error()); 
} 
+0

借你能嘗試把'$ csv'引號'LOAD DATA INFILE「$ csv''或反引號?這可能是問題所在。或者嘗試LOAD DATA INFILE'csv_file.csv'(示例文件名),如果您在Windows平臺上,則最常使用'\ r \ n'。 –

+0

另外,'$ csv'變量來自哪裏並用於?你不會讓我們繼續下去。別的東西可能會破壞你的代碼。 –

+0

@ Fred-ii-根據聲明文件的錯誤,它看起來很明顯。你所描述的問題也可能是這裏的問題。 – Ohgodwhy

回答

2

下面的例子是從靠近頁面底部http://dev.mysql.com/doc/refman/5.5/en/load-data.html拍攝。

"LOAD DATA INFILE '$myFile'" . " INTO TABLE test FIELDS TERMINATED BY '|' LINES TERMINATED BY '\n' 

它顯示了封裝在引號中的文件的變量。

嘗試以下方法:

LOAD DATA INFILE '$csv' INTO TABLE safety_quiz FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n' (first_name, last_name, person_id, quiz_result) 

正如Ohgodwhy stated in a comment在於$csv變量不正確地封裝,因此字面解釋。

或者封裝在單引號和雙引號用點:

LOAD DATA INFILE '".$csv."' 

this answer on SO

+0

將$ csv放入引號中導致「無法獲得'/var/lib/import/import_20_01_2014.csv'(Errcode:2)的狀態」 – IlludiumPu36

+0

您可以從我的OP中看到變量$ csv被解釋爲沒有引用... – IlludiumPu36

+0

然後,其他事情正在破壞你的代碼。你可以在你的問題中發佈完整的代碼嗎? @PeterBrowne –