简体   繁体   中英

How can I get an upload file from user to my database to specific user logged in?

I have a feature below which is an upload picture feature which allows users to upload a picture of themselves. It is meant to upload the picture to a directory, and then store in a database (whichever user is logged in) and also should display for the user. What seems to be happening for me is that it is inserting into the database as an 'Array' but not sure who I can get it to link to UserID I have logged in?

See code below:

error_reporting(E_ALL);
ini_set('display_errors', 1);
include("dbConnect.php");

if(isset($_POST['submit'])) {
    $file = $_FILES['file'];

    $fileName = $_FILES['file']['name'];
    $fileTmpName = $_FILES['file']['tmp_name'];
    $fileSize = $_FILES['file']['size'];
    $fileError = $_FILES['file']['error'];
    $fileType = $_FILES['file']['type'];

    $fileExt = explode('.', $fileName);
    $fileActualExt = strtolower(end($fileExt));

    $allowed = array(
        'jpg',
        'jpeg',
        'png',
        'pdf'
    );
    if(in_array($fileActualExt, $allowed)) {
        if($fileError === 0) {
            if($fileSize < 1000000) {
                $fileNameNew = uniqid('', true) . "." . $fileActualExt;
                $fileDestination = 'uploads/' . $fileNameNew;
                move_uploaded_file($fileTmpName, $fileDestination);
                header("Location: myProfile.php?successCode=1");
                echo "<img src=" . $fileDestination . " height=200 width=300/>";
            } else {
                echo "your file too big";
            }
        } else {
            echo "There was error uploading file";
        }
    } else {
        echo "you cant upload files of this type";
    }
    // Insert record
    $stmt = $conn->prepare("INSERT into Profile(ProfilePicture) values('" . $file . "')");
    $stmt->execute();
}

The problem is you are saving an array to your database. You cannot just save a picture to your database, but you CAN save the PATH to your image.

$stmt = $conn->prepare("UPDATE Profile SET ProfilePicture='{$fileName}' WHERE UserID='{$_SESSION['currentUserID']}'");

The above will save just the name of the file, so if your image directory never changes, this should be good enough and you can reference the actual directory in your code elsewhere.

-- "I want the code to insert the ProfilePicture where UserID=UserID logged in?" - In regards to this from the comments, I updated my answer to show you how to UPDATE the table where UserID='$_SESSION['currentUserID']'

NOTE: You should consider switching to prepared statements with parameterized variables , as the method currently in use may be vulnerable to SQL Injection .

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