Issue with Updating Database After Uploading a File
I am trying to upload the file and then insert the file name into the database.
Below is my code:
<?php
//connecting to database
session_start();
include('/applications/MAMP/htdocs/connect.php');
$u = $_SESSION['username'];
if (!empty($_FILES)) {
$file = $_FILES['Filedata'];
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
// $fileTypes = str_replace('*.','',$_REQUEST['fileext']);
// $fileTypes = str_replace(';','|',$fileTypes);
// $typesArray = split('\|',$fileTypes);
// $fileParts =开发者_如何学Python pathinfo($_FILES['Filedata']['name']);
// if (in_array($fileParts['extension'],$typesArray)) {
// Uncomment the following line if you want to make the directory if it doesn't exist
// mkdir(str_replace('//','/',$targetPath), 0755, true);
$n = $file['name'];
move_uploaded_file($tempFile,$targetFile);
echo str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetFile);
mysqli_select_db($connect,"people");
$i = "update users set filelocation = '$n' where sessionusername = '$u'";
$q = mysqli_query($connect,$i);
// } else {
// echo 'Invalid file type.';
// }
}
?>
The file is being uploaded successfully, but the name is not getting updated in the database.
Please help me.
$n = $file['name']
; will return nothing since $file is not declared anywhere. You probably want to use:
$n = $_FILES['Filedata']['name'];
or anything else declared you really want to put in your DB ;-)
you have $n = $file['name'];
it should be $n = $targetFile
But first of all - clean your code ;)
I cleaned up it for you. Check if this work.
<?php
session_start();
include('/applications/MAMP/htdocs/connect.php');
mysqli_select_db("people");
if (!isset($_REQUEST['folder'])) $_REQUEST['folder'] = "";
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
move_uploaded_file($tempFile,$targetFile);
$i = "UPDATE users SET filelocation = '$targetFile' WHERE sessionusername = '{$_SESSION['username']}'";
$q = mysqli_query($i);
//debug
echo "$targetFile<br/>
$tempFile<br/>
$i<br/>";
echo mysqli_error();
}
else {
echo "No file";
}
?>
精彩评论