Creating a Simple Image Gallery With PHP & Jquery

May 07, 2024 | PHP jQuery MySql Javascript


Hello Dev,

Today, we'll explore how to build a straightforward image gallery CRUD (Create, Read, Update, Delete) system using Bootstrap, MySQL database, FancyBox, and PHP. This tutorial will provide a step-by-step example from scratch, making it simple to understand the entire script.

Image galleries are commonly needed in various applications for users, employees, administrators, students, etc. A photo album facilitates easy image uploads and removals with proper validation. We aim to construct a well-designed Bootstrap layout for the image gallery in this tutorial, enabling seamless integration into your projects. Additionally, I've implemented comprehensive validation using sessions to display error and success messages. Upon successful image insertion, the user will receive a clear success message.

In this example, we'll create an "image_gallery" table with primary columns for 'title' and 'image'. I've organized the code into separate files for displaying forms, handling error messages, validation, etc. By the end of this tutorial, you'll achieve a layout similar to the preview below:

Creating a simple image gallery CRUD (Create, Read, Update, Delete) system using Bootstrap, MySQL, FancyBox, and PHP involves several steps. This guide will walk you through creating an image gallery from scratch, including setting up the database, creating the necessary PHP files for handling CRUD operations, and integrating FancyBox for a dynamic gallery view.

Step 1: Set Up Your Environment

Ensure you have PHP and MySQL installed on your server.
Install Composer to manage PHP dependencies.
Download and include Bootstrap, jQuery, and FancyBox in your project.

Read Also: Prevent Enter Key Submission Except Textarea Example Step 2: Create the Database

Create a MySQL database and a table named image_gallery with the following structure:

CREATE DATABASE image_gallery_db;

USE image_gallery_db;

CREATE TABLE image_gallery (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    image VARCHAR(255) NOT NULL
);
Step 3: Configure Database Connection

Create a db_config.php file to configure your database connection:

<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "image_gallery_db";

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

// Check connection
if ($conn->connect_error) {
    die("Connection failed: ". $conn->connect_error);
}
?>
Step 4: Create the Image Upload and Display Files imageUpload.php

This file handles image uploads and inserts the image data into the database.

<?php

session_start();
require('db_config.php');

if(isset($_POST) && !empty($_FILES['image']['name']) && !empty($_POST['title'])){
    $name = $_FILES['image']['name'];
    list($txt, $ext) = explode(".", $name);
    $image_name = time().".".$ext;
    $tmp = $_FILES['image']['tmp_name'];

    if(move_uploaded_file($tmp, 'uploads/'.$image_name)){
        $sql = "INSERT INTO image_gallery (title, image) VALUES ('".$_POST['title']."', '".$image_name."')";
        $mysqli->query($sql);
        $_SESSION['success'] = 'Image Uploaded successfully.';
        header("Location: http://localhost:8000");
    }else{
        $_SESSION['error'] = 'image uploading failed';
        header("Location: http://localhost:8000");
    }
}else{
    $_SESSION['error'] = 'Please Select Image or Write title';
    header("Location: http://localhost:8000");
}
?>
Read Also: Laravel 11 Request Validation Error Ajax Example Step 5: Integrate FancyBox

Include FancyBox CSS and JS in your HTML file to enable the lightbox gallery view.

Initialize FancyBox in your JavaScript:

index.php
<?php
  session_start();
?>

<!DOCTYPE html>
<html>
<head>
    <title>Creating a Simple Image Gallery With PHP & Jquery -- ItErrorSolution.com</title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <!-- References: https://github.com/fancyapps/fancyBox -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.min.css" media="screen">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.min.js"></script>

    <style type="text/css">
    .gallery
    {
        display: inline-block;
        margin-top: 20px;
    }
    .close-icon{
    border-radius: 50%;
        position: absolute;
        right: 5px;
        top: -10px;
        padding: 5px 8px;
    }
    .form-image-upload{
        background: #e8e8e8 none repeat scroll 0 0;
        padding: 15px;
    }
    </style>
</head>
<body>

<div class="container">
    <h3>Creating a Simple Image Gallery With PHP & Jquery -- ItErrorSolution.com</h3>
    <form action="/imageUpload.php" class="form-image-upload" method="POST" enctype="multipart/form-data">

        <?php if(!empty($_SESSION['error'])){ ?>
            <div class="alert alert-danger">
                <strong>Whoops!</strong> There were some problems with your input.<br><br>
                <ul>
                    <li><?php echo $_SESSION['error']; ?></li>
                </ul>
            </div>
        <?php unset($_SESSION['error']); } ?>

        <?php if(!empty($_SESSION['success'])){ ?>
        <div class="alert alert-success alert-block">
            <button type="button" class="close" data-dismiss="alert">×</button>
                <strong><?php echo $_SESSION['success']; ?></strong>
        </div>
        <?php unset($_SESSION['success']); } ?>

        <div class="row">
            <div class="col-md-5">
                <strong>Title:</strong>
                <input type="text" name="title" class="form-control" placeholder="Title">
            </div>
            <div class="col-md-5">
                <strong>Image:</strong>
                <input type="file" name="image" class="form-control">
            </div>
            <div class="col-md-2">
                <br/>
                <button type="submit" class="btn btn-success">Upload</button>
            </div>
        </div>

    </form> 

    <div class="row">
    <div class='list-group gallery'>
            <?php
            require('db_config.php');

            $sql = "SELECT * FROM image_gallery";
            $images = $mysqli->query($sql);

            while($image = $images->fetch_assoc()){

            ?>
                <div class='col-sm-4 col-xs-6 col-md-3 col-lg-3'>
                    <a class="thumbnail fancybox" rel="ligthbox" href="/uploads/<?php echo $image['image'] ?>">
                        <img class="img-responsive" alt="" src="/uploads/<?php echo $image['image'] ?>" />
                        <div class='text-center'>
                            <small class='text-muted'><?php echo $image['title'] ?></small>
                        </div> <!-- text-center / end -->
                    </a>
                    <form action="/imageDelete.php" method="POST">
                    <input type="hidden" name="id" value="<?php echo $image['id'] ?>">
                    <button type="submit" class="close-icon btn btn-danger"><i class="glyphicon glyphicon-remove"></i></button>
                    </form>
                </div> <!-- col-6 / end -->
            <?php } ?>

        </div> <!-- list-group / end -->
    </div> <!-- row / end -->
</div> <!-- container / end -->
</body>

<script type="text/javascript">
    $(document).ready(function(){
        $(".fancybox").fancybox({
            openEffect: "none",
            closeEffect: "none"
        });
    });
</script>
</html>
Step 6: Create the Delete Functionality

Create a delete.php file to handle image deletion.

<?php

session_start();
require('db_config.php');

if(isset($_POST) && !empty($_POST['id'])){
        $sql = "DELETE FROM image_gallery WHERE id = ".$_POST['id'];
        $mysqli->query($sql);
        $_SESSION['success'] = 'Image Deleted successfully.';
        header("Location: http://localhost:8000");
}else{
    $_SESSION['error'] = 'Please Select Image or Write title';
    header("Location: http://localhost:8000");
}
?>
View Your Application
http://localhost:8000/
php -S localhost:8000
Conclusion

This guide provides a basic framework for creating an image gallery CRUD system using Bootstrap, MySQL, FancyBox, and PHP. You can expand upon this by adding more features such as image editing, user authentication, and advanced gallery layouts. Remember to secure your file uploads and database interactions to protect against common web vulnerabilities.

Thank you for your encouragement! If you have any questions or need further assistance, feel free to ask. I'm here to help!



Tags :
#PHP
#jQuery
#MySql
#Javascript
ItErrorSolution.com

ItErrorSolution.com

"Hey there! I'm a full-stack developer and proud owner of ItErrorSolution.com, based right here in India. I love nothing more than sharing handy tips and tricks with my fellow developers through easy-to-follow tutorials. When it comes to coding, I'm all about PHP, Laravel, Angular, Vue, Node, JavaScript, jQuery, CodeIgniter, and Bootstrap – been hooked on them forever! I'm all about putting in the work and staying committed. Ready to join me on this journey to coding?"