-1

I am trying to upload and save an image file to my database table. But now I am stuck with my code and I need someone to help me out. When I hit my save button it will echo failure to save file.

profile.php

<div class="profile">
<form action="photo.php" method="POST" enctype="multipart/form-data">
        <h2>Upload File</h2>
        <label for="fileSelect">Filename:</label>
        <input type="file" name="photo" id="fileSelect">
        <input type="submit" name="submit" value="save">
        <p><strong>Note:</strong> Only .jpg, .jpeg, .gif, .png formats allowed to a max size of 5 MB.</p>
    </form>
</div>

save.php

<?php
include 'db.php';

if(isset( $_POST['photo'])){
$photo = $_POST['photo'];
$sql = "INSERT INTO users (photo) VALUE ('$photo')";
$query = mysqli_query($conn,$sql);
header("Location:profile.php");
}else{
 echo "failure to save file!";
}
?>
4
  • use mysqli_error() to find out the error message Commented May 22, 2017 at 8:51
  • do not save images directly like this. Commented May 22, 2017 at 8:52
  • Rather than storing the image file in the database, you should consider storing it within the file system and then just store the path to it. For example, you upload image named "file1.png" and all your images are stored in an "images" folder then you can just store "file1.png" in your database as a varchar Commented May 22, 2017 at 8:52
  • Take reference from here:-stackoverflow.com/a/17718807/4248328 (but stick with your mysqli_* syntax) Commented May 22, 2017 at 8:52

2 Answers 2

2

2 possibilites:

1 Save to file server(prefered):

Save the image on your file server and save the path where you saved it in the database. This allows you to directly access this file and helps you to better output it to the user than with the second method. I'd prefer this.

Explanation: upload file with php and save path to sql

2 Save to database:

You can save the content of images to a BLOB (Binary large object).

Explanation: Insert Blobs in MySql databases with php

Sign up to request clarification or add additional context in comments.

Comments

1

You need to only save the image path in your database, you need to store the image itself in a destination local to your project. Then you can use your saved path in your DB to load your image.

This answer here gives you an example exactly how to do this: How to store images in mysql database using php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.