PHP Image/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 –

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

This HTML document includes a PHP script for handling image uploads and presents a form allowing users to upload multiple images using the POST method and “multipart/form-data” enctype.

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>

Explanation –

  • The PHP script “image-upload-script.php” is included at the beginning of the HTML document.
  • The HTML document defines a form using the POST method and “multipart/form-data” enctype for multiple file uploads.
  • An input element with the name “image_gallery[]” allows users to select multiple images.
  • The form includes a submit button with the name “submit” and the label “Upload Now.”
  • Users can choose and upload multiple images using this form.

4. Write Image Upload Script

This PHP script manages the upload of multiple images, validates file types, and inserts the image names into a specified database table. It includes error handling and echoes success or error messages accordingly.

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;
       }
      }
    }     
    
?>

Explanation –

  • The PHP script includes a database connection from “database.php” and sets the connection variable and table name.
  • It checks if the form is submitted and calls the upload_image function, which handles multiple image uploads and returns an error message or success confirmation.
  • The upload_image function specifies the upload directory, allowed image types, and processes each selected image, storing valid ones in the designated folder and creating a string of image names for database insertion.
  • It validates that images and a table name are provided, returning appropriate errors if not.
  • The save_image function inserts the image names into the specified database table and echoes success or error messages based on the execution result.

Show Image Gallery with PHP

Now, display the image gallery using the following steps –

1. Write Image Gallery Script

This PHP script connects to a database, defines a function (fetch_image) to retrieve image data from a specified table, and echoes appropriate messages based on the outcome, including displaying the images or indicating no images or an undefined 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";
}
}  

?>

Explanation –

  • The PHP script includes a database connection from “database.php” and sets the connection variable and table name.
  • The script defines a function, fetch_image, which retrieves image data from the specified database table ordered by ID in descending order.
  • If the table name is provided and valid, the function fetches and returns the image data in an associative aray.
  • If no images are found in the database, it echoes a message stating that no images are stored.
  • If no table name is provided, it echoes a message instructing to declare a table name to fetch images.

2. Show Image Gallery

This HTML document displays an image gallery with rows and columns generated dynamically from fetched image data using PHP. It includes a modal for larger image views, navigation buttons, and captions, with additional functionality provided by a linked JavaScript file. If no images are present, a corresponding message is displayed.

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>

Explanation –

  • The PHP script “image-gallery-script.php” is required at the beginning of the HTML document.
  • The HTML document includes a viewport meta tag, a link to a stylesheet (“assets/style.css”), and a body tag.
  • The body contains an image gallery with rows and columns generated using PHP based on the fetched image data.
  • Each image is displayed in a div with a “hover-shadow” effect and an onclick event to open a modal and display the image.
  • A modal is used for a larger view of the images, with navigation buttons to switch between images.
  • The modal includes image slides created dynamically based on the fetched image data, and each image has a corresponding slide in the modal.
  • The modal has a close button, navigation arrows, and a caption container.
  • The HTML document includes a script tag linking to “assets/gallery-script.js” for additional functionality.
  • JavaScript functions like openModal, closeModal, plusSlides, and currentSlide are used for modal navigation and interaction.
  • If no images are fetched, a message is echoed indicating that no images are saved in the database.

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.