简体   繁体   中英

How do I store the name and the path of the file in my database?

Uploading the file is okay, but storing the path and the name of the file into my database is not.

This is my form 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>

And here is my action file

<?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.";
        }
    }
}
?>

I`am trying to get the filename and the path to store it in my database

It's always worth checking for and reporting errors.

In your INSERT, (p.desc) is trying to find a table called p (usually an alias) which isn't defined. Try...

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

(Without the p. ).

BUT I still recommend using prepared statements, have a read of How to create a secure mysql prepared statement in php?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM