PHP Image Gallery – Create Photo Gallery with Database

PHP Image Gallery:  Using the source code of this tutorial, You can easily create a simple & dynamic photo gallery with a database in a PHP script.

The image gallery is the most popular feature of the web application. It is used to display a collection of dynamic images on the web page. Here you will learn it through some easy steps that are very simple to understand.

First of all, You have to store some images to the server from the admin panel. After then, you can show them in the form of a gallery by fetching from a folder & MYSQL database. So, you will get standard scripts to quickly implement it in your project.

I have created an attractive & responsive PHP photo gallery with a popup model and slider feature.

php image gallery

How to create dynamic photo gallery in PHP

You can create a dynamic photo/image gallery with PHP through the following steps –

Learn Also –

Compress Image Size in PHP without Losing Quality

First of all, You have to create the following folder structure

myproject
   |__assets/
   |    |__gallery-script.js
   |    |__style.css
   |__uploads/
   |__database.php
   |__image-gallery-script.php
   |__image-upload-form.php
   |__image-upload-script.php
   |__show-image-gallery.php

Create Image Gallery in PHP

To create an image gallery with a database, you have to configure the following steps –

1. Create MySQL Database and table

Use the following MYSQL query to create a database with the name codingstatus

Also, Use the following MYSQL query to create a table with the name gallery

Table Name – gallery

CREATE TABLE `gallery` (
`id` int(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
`image_name` varchar(255) DEFAULT NULL,
) ENGINE=InnoD

2. Connect PHP to MYSQL Database

Now, use the following MySQL query to connect PHP to the database.

File Name database.php

<?php

$hostname     = "localhost";
$username     = "root";
$password     = ""; 
$databasename = "codingstatus"; 
// Create connection 
$conn = new mysqli($hostname, $username, $password,$databasename);
 // Check connection 
if ($conn->connect_error) { 
die("Unable to Connect database: " . $conn->connect_error);
 }
?>

3. Create Image Upload Form

To create an image upload form, use the following points –

  • Include image-upload-script.php
  • Create an HTML form, file upload browse button & submit button with the following attributes
    • method= “post” – It uploads an image with security.
    • enctype= “multipart/form-data” – It allows different type of image extension.
    • type=” file”  – It creates a file upload browse button.
    • name= “image_gallery[]” – It access multiple images in an array.
    • multiple  – It allows us to select more than one image at a time.
    • type= “submit”  – It sends image value to the server.
    • name= “submit”  – It accesses whole input values to submit the form.

File Name – image-upload-form.php

 <?php

include('image-upload-script.php');
?>

<!DOCTYPE html>
<html>
<body>

<form  method="post" enctype="multipart/form-data">
    <input type="file" name="image_gallery[]" multiple>
    <input type="submit" value="Upload Now" name="submit">
</form>

</body>
</html>

 

4. Write Image Upload Script

This script will help you to upload multiple images to the server. you have to configure the following some steps to create it –

  • Include the database connection file database.php.
  • Assign $conn variable to a new variable $db
  • Assign your table name gallery to a variable $tableName
  • Call custom function upload_image() on submit the form.
  • upload_image() – This function is created to upload multiple images.
  • save_image() –  This function is created to save an image into the MySQL database.

File Name image-upload-script.php

<?php

require_once('database.php');

$db=$conn; // Enter your Connection variable;
$tableName='gallery'; // Enter your table Name;


// upload image on submit
if(isset($_POST['submit'])){ 
    echo upload_image($tableName); 
}

  function upload_image($tableName){
   
    $uploadTo = "uploads/"; 
    $allowedImageType = array('jpg','png','jpeg','gif');
    $imageName = array_filter($_FILES['image_gallery']['name']);
    $imageTempName=$_FILES["image_gallery"]["tmp_name"];

    $tableName= trim($tableName);

if(empty($imageName)){ 
   $error="Please Select Images..";
   return $error;
}else if(empty($tableName)){
   $error="You must declare table name";
   return $error;
}else{
   $error=$savedImageBasename='';
   foreach($imageName as $index=>$file){
         
    $imageBasename = basename($imageName[$index]);
    $imagePath = $uploadTo.$imageBasename; 
    $imageType = pathinfo($imagePath, PATHINFO_EXTENSION); 

 if(in_array($imageType, $allowedImageType)){ 

    // Upload image to server 
    if(move_uploaded_file($imageTempName[$index],$imagePath)){ 
        
    // Store image into database table
     $savedImageBasename .= "('".$imageBasename."'),";     
    }else{ 
     $error = 'File Not uploaded ! try again';
  } 
}else{
    $error .= $_FILES['file_name']['name'][$index].' - file extensions not allowed<br> ';
 }
 }
    save_image($savedImageBasename, $tableName);
}
    return $error;
}
    // File upload configuration 
 function save_image($savedImageBasename, $tableName){

      global $db;
      if(!empty($savedImageBasename))
      {
      $value = trim($savedImageBasename, ',');
      $saveImage="INSERT INTO ".$tableName." (image_name) VALUES".$value;
      $exec= $db->query($saveImage);
      if($exec){
        echo "Images are uploaded successfully";  
       }else{
        echo  "Error: " .  $saveImage . "<br>" . $db->error;
       }
      }
    }     
    
?>

 

Show Image Gallery with PHP

Now, display the image gallery using the following steps –

1. Write Image Gallery Script

This script will help you to fetch images from the database. To create it, you will have to go through the following points –

  • Include database connection file database.php
  • Assign $conn variable to another variable $db
  • Assign your table name gallery to a new variable $tableName
  • Create a custom function fetch_image($tableName) with a parameter that will accept only table Name and call it by assigning to a variable $fetchImage. This function contains a MySQL SELECT query to select all the values of images from the table.

File Name – image-gallery-script.php

 <?php

require_once('database.php');

$db=$conn; // Enter your Connection variable;
$tableName='gallery'; // Enter your table Name;

$fetchImage= fetch_image($tableName);

      // fetching padination data
function fetch_image($tableName){
   global $db;
   $tableName= trim($tableName);
   if(!empty($tableName)){
  $query = "SELECT * FROM ".$tableName." ORDER BY id DESC";
  $result = $db->query($query);

if ($result->num_rows > 0) {
    $row= $result->fetch_all(MYSQLI_ASSOC);
    return $row;       
  }else{
    
    echo "No Image is stored in the database";
  }
}else{
  echo "you must declare table name to fetch Image";
}
}  

?>

 

2. Show Image Gallery

To show the image gallery on the web page, you will have to configure the following things –

  • Include image gallery script file image-gallery-script.php to fetch images from the database.
  • Include stylesheet file style.css  to design a photo gallery in the head section.
  • Print images with foreach loop applies on $fetchImage.
  • Include javascript file gallery-script.js to create a Modal & slider of the photo gallery.

File Name show-image-gallery.php

<?php

require('image-gallery-script.php');
?>

<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="assets/style.css">

<body>

<!--======image gallery ========-->
<br>
<div class="row">
    
<?php

  if(!empty($fetchImage))
  {
    $sn=1;
    foreach ($fetchImage as $img) {
        
?>

    <div class="column">
    <img src="uploads/
<?php
echo $img['image_name']; 
?>
" style="width:100%" onclick="openModal(); currentSlide(
<?php
echo $sn; 
?>
)" class="hover-shadow cursor">
  </div>
<?php

 $sn++;}
  }else{
    echo "No Image is saved in database";
  }
?>

</div>
<!--======image gallery ========-->


<div id="galleryModal" class="modal">
  <span class="close cursor" onclick="closeModal()">&times;</span>

  <!--======image gallery modal========-->
  <div class="modal-content">
      
<?php

  if(!empty($fetchImage))
  {
    $sn=1;
    foreach ($fetchImage as $img) {
        
?>
<div class="gallerySlides">
      <div class="numbertext"> / 4</div>
      <img src="uploads/
<?php
echo $img['image_name']; 
?>
" style="width:100%">
    </div>
<?php

 $sn++;}
  }else{
    echo "No Image is saved in database";
  }
?>


   <!--======image gallery model========-->
    
    <a class="prev" onclick="plusSlides(-1)">&#10094;</a>
    <a class="next" onclick="plusSlides(1)">&#10095;</a>

    <div class="caption-container">
      <p id="caption"></p>
    </div>
  </div>
</div>

<script type="text/javascript" src="assets/gallery-script.js"></script>
    
</body>
</html>

 

3. Design Image Gallery Using CSS

Use the following CSS code to design the image gallery. you can also add your CSS code according to your project requirement

File Name – style.css

body {
  box-sizing: border-box;
  margin:0px;
  padding: 0px;
  overflow-x: hidden;
}
.row > .column {
  margin: .5%; 
}
.row:after {
  content: "";
  display: table;
  clear: both;
}
.column {
  float: left;
  width: 24%;
}
.modal {
  display: none;
  position: fixed;
  z-index: 1;
  padding-top: 100px;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: #363333ab;
}
.modal-content {
  position: relative;
  background-color: #fefefe;
  margin: auto;
  padding: 0;
  width: 90%;
  max-width: 1200px;
}
.close {
  color: white;
  position: absolute;
  top: 10px;
  right: 25px;
  font-size: 35px;
  font-weight: bold;
}
.gallerySlides {
  display: none;
}
.cursor {
  cursor: pointer;
}
.prev, .next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  padding: 16px;
  margin-top: -50px;
  color: white;
  font-weight: bold;
  font-size: 20px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
  user-select: none;
  -webkit-user-select: none;
  background: #00000066;
}
.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}
.numbertext {
    color: #171717;
    font-size: 20px;
    padding: 8px 12px;
    position: absolute;
    top: 0;
    font-weight: bold;
}
.column img{
    max-height: 160px;
    height: 160px;
    object-fit: contain;
    padding: 5px;
    border: 1px solid #d9d9d9;
}
.caption-container {
  text-align: center;
  background-color: black;
  padding: 2px 16px;
  color: white;
}
img.hover-shadow {
  transition: 0.3s;
}
.hover-shadow:hover {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}

 

4. Create Image Gallery Model Using javascript

You have created the following functions for creating an Image gallery model –

  • openModal() – It can open the image model
  • closeModal() – It can close the opened image model
  • showSlides(n) – It works to slide images in the gallery

File Name gallery-script.js

function openModal() {
  document.getElementById("galleryModal").style.display = "block";
}

function closeModal() {
  document.getElementById("galleryModal").style.display = "none";
}

var slideIndex = 1;
showSlides(slideIndex);

function plusSlides(n) {
  showSlides(slideIndex += n);
}

function currentSlide(n) {
  showSlides(slideIndex = n);
}

function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("gallerySlides");
  var captionText = document.getElementById("caption");
  if (n > slides.length) {slideIndex = 1}
  if (n < 1) {slideIndex = slides.length}
  for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none";
  }

  slides[slideIndex-1].style.display = "block";

}

 

Tutorial Summary –

I hope you like this tutorial. Even it is useful for you. So, Don’t forget to share with friends who need it.

If you have any queries, you can ask me through the below comment box. I will also share more PHP source code. So, you should continue to visit my blog for becoming an expert in the coding field.

Leave a Comment