-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!";
}
?>
C Francis
  • 43
  • 1
  • 9
  • use `mysqli_error()` to find out the error message – Jens May 22 '17 at 08:51
  • do not save images directly like this. – Rotimi May 22 '17 at 08: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 – Luke K May 22 '17 at 08:52
  • Take reference from here:-http://stackoverflow.com/a/17718807/4248328 (but stick with your `mysqli_*` syntax) – Alive to die - Anant May 22 '17 at 08:52

2 Answers2

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

Community
  • 1
  • 1
Marvin Fischer
  • 2,552
  • 3
  • 23
  • 34
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

Community
  • 1
  • 1
Nick Howarth
  • 511
  • 4
  • 21