简体   繁体   中英

How to save an image to the database with a path file

I am trying to save a picture into my database along with the path file. But what it does now is incorrect. It only saves the image into the database and not the entire image path. What's wrong?

I do the exact same thing with this code in another project and can't wrap my head around the problem here.

$userPic = '';
$date_time = date('Y-m-d_H-i-s');

if(!empty($userLoggedIn)) {

    if (isset($_FILES['fileToUpload'])) {
        $errors = array();
        $file_name = $_FILES['fileToUpload']['name'];
        $file_size = $_FILES['fileToUpload']['size'];
        $width = 1500;
        $height = 1500;
        $file_tmp = $_FILES['fileToUpload']['tmp_name'];
        $file_type = $_FILES['fileToUpload']['type'];
        $tmp = explode('.', $_FILES['fileToUpload']['name']);
        $file_ext = strtolower (end ($tmp));

        $extensions = array("jpeg", "jpg", "png", "gif");

        if(in_array($file_ext, $extensions) === false) {

            $errors[] = "extension not allowed. Please choose a JPEG or PNG file.";
        }

        if ($file_size > 8097152) {

            $errors[] = 'File size must be 2 MB';
        }

        if ($width > 1500 || $height > 1500) {

            echo"File is to large";
        }

        if(!$errors) {

            $userPic = md5($_FILES["fileToUpload"]["name"]) . $date_time . " " . $file_name;
            move_uploaded_file($file_tmp, "assets/images/profile_pics/" . $userPic);

            $stmt = $con->prepare("UPDATE users SET profile_pic = ? WHERE username = ?");
            $stmt->bind_param('ss', $userPic, $username);
            $stmt->execute();
            $stmt->close();
        }
    }
}
else {
    echo "Invalid Username";
}

You can assign another variable that contains both the path and the variable for the image you used, and then use that variable in your query:

$file_path = "assets/images/profile_pics/".$userPic;

Your code:

if(!$errors) {

    $userPic = md5($_FILES["fileToUpload"]["name"]) . $date_time . " " . $file_name;
    move_uploaded_file($file_tmp,"assets/images/profile_pics/" . $userPic);
    $imag_path = "assets/images/profile_pics/" . $userPic;
    $stmt = $con->prepare("UPDATE users SET profile_pic = ? WHERE username = ?");
    $stmt->bind_param('ss', $imag_path, $username);
    $stmt->execute();
    $stmt->close();
}

Try this:

You save only the new image name, not path.

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