Welcome folks today in this blog post we will be building a image gallery crud app in php and mysql database using fancybox database. All the full source code of the application is shown below.
Get Started
In order to get started you need to install the xammp control panel for the mysql database. First of all you need to install it from here and then after that you need to start the apache server and mysql database.
Directory Structure of App
Now we will see the directory structure of App as shown below
As you can see we have the uploads folder where we will be storing all the images which will be uploaded by the user. And also we have the php files to perform the crud operations. And then we have the db_config.php file which is used to connect to the database.
Connecting to MySQL Database
Here we are connecting to MySQL Database using the below php file. First of all you need to make a db_config.php
file inside the root directory and copy paste the below code
db_config.php
1 2 3 4 |
<?php $mysqli = new mysqli("localhost","root", "","imagecrud"); ?> |
As you can see we are passing the hostname,username,password and database name. Here we are using the mysqli() method to connect to the mysql database.
Making the Index.php File
Now we will be making the index.php
file in the root directory of the project. First of all we will be importing the dependencies of bootstrap cdn and fancybox cdn libraries for image animations
index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php session_start(); ?> <!DOCTYPE html> <html> <head> <title>Image Gallery Example</title> <!-- Latest CSS which is minified and compiled --> <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> </head> <body> </body> <script> </script> </html> |
As you can see we are importing all the libraries cdn of bootstrap and fancybox. And also we are importing the jquery library cdn as well. And also we are starting the session of the app using the session_start() method.
Creating the Table in PHPMyAdmin
Now we will be creating the table inside the phpmyadmin section as shown below. First of all you need to create the database and then create the tables.
As you can see we are creating the database which is called imagecrud
and then now we need to create the tables as shown below
As you can see we have five columns inside the table which is id which will be the primary key of the table and autoincremented. And then we have the text field called title which holds the title of the image. And then we have the varchar field called image which will hold the path of the image and then we have two timestamps variables to store the timestamps.
Upload Images Using HTML5 Form
Now we will be uploading images using html5 form. So again inside the index.php
file you need to write the below code
index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<h3> Example of Image Gallery CRUD using PHP MySQL </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> Our input faces some problems. <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> |
As you can see we have the two input fields which is for the title of the image and the input file for uploading images and also we have the button to upload images as shown below
As you can see we have the bootstrap form to upload images. And we have given the action attribute to the html5 form when we submit the html5 form we have the route /imageUpload.php
. And also we are showing the error and success messages that will be coming from the php file. And displaying it using the session variables.
Uploading the Images in PHP
Now we will be uploading the images using the php script. First of all we need to create imageUpload.php file inside the root directory and copy paste the below code
imageUpload.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?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'] = 'Uploading of image is successfully.'; header("Location: index.php"); }else{ $_SESSION['error'] = 'Uploading of image is failed'; header("Location: index.php"); } }else{ $_SESSION['error'] = 'Please Select Image or Write title'; header("Location: index.php"); } ?> |
As you can see first of all we are importing the db_config.php
file at the top of the file for connecting to the database and the table. And then we are checking the POST variables that are sent from the html5 form. We are using the isset method to check the title and the image that we sent from form. And then we are getting the name from the $_FILES array. And then we are using the explode() method to extract the title and the extension of the image. And then we are using the move_uploaded_files()
method to move the input image to the temp location and this method returns boolean parameter. If it returns to true then we are uploading the image to uploads
folder. And after that we are inserting the path of the image and the title of the image to the mysql table and then we are setting the session variable of success and then we are redirecting the user to the homepage. And if any error takes place we are setting the error session variable and redirecting to the homepage.
Now if we open the application inside the browser try to write the title and upload the image and then if you try to upload the image you will see the below result as shown below
As you can see we have the bootstrap alert success message which we display inside the user interface. And also we are inserting the records inside the mysql table. And also the image is uploaded and stored inside the uploads folder as shown above.
Displaying All Uploaded Images in Gallery
Now we will be displaying all the images in the form of the gallery. First of all we need to copy paste the below code inside the index.php
file as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
<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> <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="http://localhost/imagegallery/uploads/<?php echo $image['image'] ?>"> <img width="800" height="800" class="img-responsive" alt="" src="http://localhost/imagegallery/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'] ?>"> <input type="hidden" name="name" value="<?php echo $image['image']?>"> <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 --> |
As you can see we are displaying all the images in the form of gallery. And also we are applying some custom css for styling the below images in the form of a grid. For this first of all we are importing the database connection file called db_config.php
at the very top. And then we are using the select operation to get all the images from the table and then we are converting the resultant images to an associative array. And then we are looping through the array and the images and displaying it inside the html. So we are given fancy bootstrap image classes to make it look responsive and also we are initializing the fancybox library so that when we click the image then it will show larger in size. Also in the <small> tag we are showing the title of the image. And also we have the cross button to actually delete the image. So we have the html5 form for that delete operation. As you see when we click that cross button then it goes to the imageDelete.php
file using the action attribute. All the delete code will be written inside that file. So now if you execute this it will look something like this
Deleting the Images from Table and Local Disk
Now we need to create a new file called imageDelete.php
in the root directory and copy paste the below code as shown below
imageDelete.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php session_start(); require('db_config.php'); if(isset($_POST) && !empty($_POST['id']) && !empty($_POST['name'])){ $sql = "DELETE FROM image_gallery WHERE id = ".$_POST['id']; $mysqli->query($sql); $file_to_delete = './uploads/' . $_POST['name']; unlink($file_to_delete); $_SESSION['success'] = 'Deletion of image is successfully.'; header("Location: index.php"); }else{ $_SESSION['error'] = 'Please Select Image or Write title'; header("Location: index.php"); } ?> |
As you can see we are getting the id
of the image which is unique for every image because it is primary key. Using this value we are deleting the image using the DELETE operator in SQL. And also secondly we are also getting the name of the image as the second argument in this php script through the form. And using this we are deleting the actual image stored inside the local folder uploads. For deleting the image we are using the unlink() method passing the full path of the image. And after deletion we are sending success message in the session variable.
And now if we click the cross button now. Then the image will be deleted and you will get the success message as shown below
Full Source Code
Wrapping it Up Now you will see the full source code of the index.php
file as shown below
index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 |
<?php session_start(); ?> <!DOCTYPE html> <html> <head> <title>Image Gallery Example</title> <!-- Latest CSS which is minified and compiled --> <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> Example of Image Gallery CRUD using PHP MySQL </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> Our input faces some problems. <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="http://localhost/imagegallery/uploads/<?php echo $image['image'] ?>"> <img width="800" height="800" class="img-responsive" alt="" src="http://localhost/imagegallery/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'] ?>"> <input type="hidden" name="name" value="<?php echo $image['image']?>"> <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> |