Reputation: 241
I want to get the path of a selected file and store it in the database for future use. I have the following code but it does not work.
$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 is the name of my input type="file" and $path is the code i am using but it does not work. IT just returns blank.
Anyone who can help me or lead me to a different, hopefully easier method? Thank you in advance. :)
Upvotes: 1
Views: 5814
Reputation: 566
$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"
}
Also keep in mind that there can be permission issues (with the directory that you want the image to be uploaded to) while uploading the file.
Good Luck!
Upvotes: 1
Reputation: 17
Have you set your form enctype correctly on the HTML side so that it is correctly able to work as it should. Secondly, TMP is just a temporary location, you MUST move that file to a server readble directory using PHP function move_uploaded_file Read about enctypes, in this answer or on w3 schools.
<form name="YourForm" method="post" enctype="multipart/form-data" action="">
Upvotes: 1
Reputation: 1964
PHP will store submitted files in a temporary directory, which you shouldn't be storing in the database as it'll be volatile.
Use PHP's move_uploaded_file
function to move the file to where you'd like in your file system, and then store that path in your database.
Docs: http://php.net/manual/en/function.move-uploaded-file.php
Upvotes: 2