Upload Image In PHP Mysql Database And Display Demo

By : PHPErrorCode July 3, 2017 3079 Views php

In this post i want to share you how to Upload image (png, jpg, jpeg, gif, bmp) in your core php website with MySQL, If you are beginner then It is a very simple way upload image in your wbsite. And in this post I will explain how to show image so that you can easily show the image (png, jpg, jpeg, gif, bmp) into your website.

It is difficult to upload the image in the beginning stage. If I can very simple way upload image in your wbsite, this is the step by step stop...

Stap 1:  First Create a Database :
  1. Open phpmyadmin
  2. Create database   as "tutorial"
  3. Click create table and name it as "user"
CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `image` varchar(100) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
step 2: Front end code, Make HTML Structure of your image upload form for index.php

Setup a form for uploading image. Don’t forget to add enctype=”multipart/form-data” attribute, which is a common mistake most of beginners does. And always set the method to post.

<?php session_start(); ?>
<!DOCTYPE html>
<html>
<head>
  <title>Image Upload</title>
</head>
<body>
  <?php if(isset($_SESSION['err'])){ ?>
    <h2><?php echo $_SESSION['err']; ?></h2>
  <?php session_unset(); } ?>
  <form method="post" action="image_upload.php" enctype="multipart/form-data" >
    <input type="file" name="image" />
    <input type="submit" value="Submit" name="save">
  </form>
</body>
</html>
Step 3:  Create A New File config.php And Place The Code Below Into It.
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tutorial";

	// Create connection
	$conn = new mysqli($servername, $username, $password, $dbname);

	// Check connection
	if ($conn->connect_error) 
	{
	    die("Connection failed: " . $conn->connect_error);
	}
Step 4 : Store Image in Database using PHP

To store uploaded image path in database we will create a new php file name it as "image_upload.php" because in the "form" tag we gave "action" attribute target path as "image_upload.php" and in this file ("image_upload.php") all the form-data will be posted.

Let's Code "image_upload" file.

require_once('config.php');
session_start();
if(isset($_POST['save']))
{
  $target_dir = "upload/img/";
  $filename = explode('.',$_FILES['image']['name']);
  $ext = $filename[1];
  $imgname = time().'.'.$ext;
  $target_file = $target_dir . $imgname ;

  $uploadOk = 1;
  $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
  // Check if image file is a actual image or fake image
  $check = getimagesize($_FILES["image"]["tmp_name"]);
  if($check !== false) {
    $text="File is an image - " . $check["mime"] . ".";
    $uploadOk = 1;
  } else {
    $text="File is not an image.";
    $uploadOk = 0;
  }
  // Check if file already exists
  if(file_exists($target_file)) {
    $text="Sorry, file already exists.";
    $uploadOk = 0;
  }
  // Check file size
  if($_FILES["image"]["size"] > 2000000) {
    $text="Sorry, your file is too large.";
    $uploadOk = 0;
  }
  // Allow certain file formats
  if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
  && $imageFileType != "gif" && $imageFileType != "bmp" ) {
    echo "Sorry, only JPG, JPEG, PNG, GIF & BMP files are allowed.";
    $uploadOk = 0;
  }
  // Check if $uploadOk is set to 0 by an error
  if($uploadOk == 0) {
    $_SESSION["error"]=$text;
    header("Location:index.php?id=$id"); /* Redirect browser */
    exit();

  // if everything is ok, try to upload file
  }else{
    if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
      $path=$imgname;
      $conn->query("INSERT INTO user (image)VALUES ('$path')");
      $_SESSION["Success"]='Image Is Upload Success...';
      header("Location:view_image.php"); /* Redirect browser */
      exit();
    } else {
      $_SESSION["err"]=$text;
      header("Location:index.php"); /* Redirect browser */
      exit();
    }
  }
}
Step 5 : Display all uploaded images from MySQL database

You need to set the path to do the show image like src="upload/img/<?php echo $row['image']; ?>"

<?php session_start(); ?>
<!DOCTYPE html>
<html>
<head>
  <title>View Image</title>
</head>
<body>
  <?php if(isset($_SESSION['Success'])){ ?>
    <h2><?php echo $_SESSION['Success']; ?></h2>
  <?php session_unset(); } ?>
  <a href="index.php">add new image</a>
  <table border="1" width="100%">
    <tr>
      <td>id</td>
      <td>image</td>
      <td>Action</td>
    </tr>
      <?php
        include('config.php');
        $result = $conn->query("SELECT * FROM image");
        if(!$result->num_rows > 0){ echo '<h2 style="text-align:center;">No Data Faund</h2>'; }
        while($row = $result->fetch_assoc())
        {
      ?>
        <tr>
          <td><?php echo $row['id']; ?></td>
          <td><img src="upload/img/<?php echo $row['image']; ?>" width="100px" height="100px"></td>
          <td><a href="delete_image.php?id=<?php echo $row['id']; ?>">Delete</a></td>
        </tr>
      <?php } ?>
  </table>
</body>
</html>
Step 6: Deleting Record with Image

Now Put the following code just above tag within "index.php" or you can create new page to delete record like "delete_image.php" just hyperlink the page name along with record id  

require_once('config.php');
session_start();
$id=$_GET['id'];
$result = $conn->query("SELECT * FROM user WHERE id='$id'");
if($result->num_rows > 0)
{ 
    //remove image in your folder
    $row = $result->fetch_assoc();
    $path="upload/img/".$row['image'];
    unlink($path);

    //remove record in your database
    $conn->query("DELETE FROM user WHERE id='$id'");
    $_SESSION["Success"]='Delete Image Is Upload Success...';
    header("Location:view_image.php");
}
else
{
    $_SESSION["Success"]='Image Not Found...';
    header("Location:view_image.php");
}