2015-01-06 43 views
1

我想獲取選定文件的路徑並將其存儲在數據庫中以供將來使用。 我有下面的代碼,但它不起作用。如何使用php獲取input type =「file」中選定文件的路徑?

$path = $_FILES['txtImage']['tmp_name']; 
$sql = "INSERT INTO tblquestions (q_category, q_question, q_image, q_correct, q_answer2, q_answer3, q_answer4) VALUES ('$_POST[txtCategory]','$_POST[txtQuestion]','$path','$_POST[txtCorrect]','$_POST[txtChoice2]','$_POST[txtChoice3]','$_POST[txtChoice4]')"; 

txtImage是我的輸入type =「file」的名稱,$ path是我使用的代碼,但它不起作用。 IT只是返回空白。

任何人都可以幫助我或帶領我到另一個不同的希望更簡單的方法?先謝謝你。 :)

回答

1
$tmp_path = $_FILES['txtImage']['tmp_name']; 

$dest_path = path_where_in_your_server_you_want_this_image_to_be_moved.$_FILES['textImage']['name']; (eg: 'images/'.$_FILES['name']) 

if(move_uploaded_file($tmp_path,$dest_path)){ //this will move the file from tmp location in server to the destination you provide in the second parameter 

$sql = "INSERT INTO tblquestions (q_category, q_question, q_image, q_correct, q_answer2, q_answer3, q_answer4) VALUES ('$_POST[txtCategory]','$_POST[txtQuestion]','$dest_path','$_POST[txtCorrect]','$_POST[txtChoice2]','$_POST[txtChoice3]','$_POST[txtChoice4]')"; 

}else{ 

echo "Image could not be uploaded" 

} 

服務器readble目錄還請記住,可以有權限問題(上傳文件時需要上傳圖片的目錄)。

祝你好運!

+0

謝謝。這工作。 :) – Nek

2

PHP將提交的文件存儲在一個臨時目錄中,您不應該將其存儲在數據庫中,因爲它會變得不穩定。

使用PHP的move_uploaded_file函數將文件移動到文件系統中的所需位置,然後將該路徑存儲在數據庫中。

文檔:http://php.net/manual/en/function.move-uploaded-file.php

+0

我明白你的建議。但我不知道如何編輯我的代碼。我是新來的PHP。你能幫我重新創建我的代碼嗎?任何領導將不勝感激。 – Nek

1

你有沒有正確設置表單的enctype在HTML端,使其能夠正確的,因爲它應該工作。 其次,TMP只是一個臨時位置,你必須在文件移動到使用PHP function move_uploaded_file 閱讀有關enctypes,in this answeron w3 schools.

<form name="YourForm" method="post" enctype="multipart/form-data" action=""> 
相關問題