如何在数据库中存储文件的名称和路径?

时间:2018-07-22 06:05:19

标签: php mysqli file-upload

可以上传文件,但是不能将路径和文件名存储到我的数据库中。

这是我的HTML表单。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">

  

<form action="../model/uploadcredentials.php" method="POST" enctype="multipart/form-data">
    <input type="file" name="fileToUpload" placeholder="Upload your credentials">
    <button type="submit" name="submit">Upload</button>
</form>

这是我的操作文件

<?php
if(isset($_FILES["fileToUpload"]["name"]))
{
    $target_dir = "../assets/credentials/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
    // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;

        } else {
            echo "File is not an image.";
            $uploadOk = 0;
        }
    }
    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) 
        {
            echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";

            $file = stripcslashes($_FILES["fileToUpload"]["name"]);
            $file = mysqli_real_escape_string($con,$file);
            $query = $con->query("INSERT INTO `portfolio`(p.desc) VALUES('$file')");
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
}
?>

我正在尝试获取文件名以及将其存储在数据库中的路径

1 个答案:

答案 0 :(得分:0)

总是值得检查并报告错误。

在您的INSERT中,(p.desc)试图找到一个未定义的名为p(通常是别名)的表。试试...

$query = $con->query("INSERT INTO portfolio(desc) VALUES('$file')");

(没有p.)。

但我仍然建议使用准备好的语句,请阅读How to create a secure mysql prepared statement in php?