Updated date:

Dynamically Display Images in Image Slider using PHP and MySql

Timothy is an enthusiast programmer and loves developing websites. He is expert in HTML, CSS, JavaScript, PHP, C#, and ASP[dot]NET.

dynamically-display-images-in-image-slider-using-php-and-mysql

Introduction

Image sliders are very good option to give an attractive look to your website as well as to display valuable information. Today most of the websites have image slider on front page. Image sliders are used to rotate images at specified interval.

For example have a look on ‘My Government' website of Government of India in following image which has an image slider that display most recent updates.

Image Slider at MyGov.in

Image Slider at MyGov.in

The problem arises with such image slider is that you need to modify code whenever you plan to update either images or the number of images you wish to change. And sometimes changing the code becomes cumbersome task and you may also be at risk of accidentally modifying other lines of code.

Therefore to solve such problem, we need a way to change image without handling code. And one solution is to upload image into database and display those images on slider from database. In this way when an image on slider needs to be change, it should be uploaded to database.

To understand implementing the process I have divided this article into two sections. First section explains about uploading the image and second section to display image on slider.

Point to Note

There are many image carousels or sliders available on web. For this example I am using JSSOR slider which can be downloaded freely.

Section 1: Uploading the Image to Database

To upload image to database a table should be created. The code for creating table is given below:

CREATE TABLE IF NOT EXISTS `images` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `image` longblob NOT NULL,
  `created` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

Remember, in this example I am uploading image directly in database table. For this I have specified field ‘image’ as type ‘LONGBLOB’. 'LONGBLOB' is a type which is used to store binary data, and since images are nothing but binary data we require this field.

The other way of storing image is to upload it to a dedicated directory of web server and name and path of uploaded image should be stored in database.

Next, I have created a simple HTML interface to upload image to database. It contains HTML file control to select image file from computer and a button to upload it. Please look at the code given below

Upload.html

<!DOCTYPE html>
<html lang="en">
<body>
    <form action="store.php" method="post" enctype="multipart/form-data">
        Select image to upload:
        <input type="file" name="image"/>
        <input type="submit" name="submit" value="UPLOAD"/>
    </form>
</body>
</html>

After an image is selected and upload button is clicked the details are submitted to ‘store.php’ file having code to store it in database. Following code illustrate the functionality:

Store.php

<?php
if(isset($_POST["submit"])){
    $check = getimagesize($_FILES["image"]["tmp_name"]);
    if($check !== false){
        $image = $_FILES['image']['tmp_name'];
        $imgContent = addslashes(file_get_contents($image));
        
         $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
        
        if($db->connect_error){
            die("Connection failed: " . $db->connect_error);
        }
        
        $dataTime = date("Y-m-d H:i:s");
        $insert = $db->query("INSERT into images (image, created) VALUES ('$imgContent', '$dataTime')");
        if($insert){
            echo "File uploaded successfully.";
        }else{
            echo "File upload failed, please try again.";
        } 
    }else{
        echo "Please select an image file to upload.";
    }
}
?>

The above PHP code simply extracts the details of image uploaded via file control, setup the database connection settings and perform the 'INSERT' operation. The output of operation is represented in following figures.

HTML Form to Upload Image

HTML Form to Upload Image

store.php file displaying message after image has been uploaded

store.php file displaying message after image has been uploaded

2. Displaying Images on JSSOR Slider

The image from database can be displayed in HTML using <img> tag. Modify this tag once to hold images from database. To do this simply search the 'slides container' in the code given with JSSOR slider and replace with the following code.

Point to Remember

Everything must be inside PHP file and not in plain HTML file.

Slider.php (A Portion of Code to Display Images from Database)

<!-- Slides Container -->
<div u="slides" style="position: absolute; left: 0px; top: 0px; width: 1140px; height: 442px;
            overflow: hidden;">
<?php
						
	//Create connection and select DB
	$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
					
	//Check connection
	if($db->connect_error){
		die("Connection failed: " . $db->connect_error);
	 }
	
        //Get image data from database
	 $result = $db->query("SELECT id, created FROM images order by created DESC  limit 3");
				
	 While($imgData = $result->fetch_assoc()){        
			echo "<div> <img data-u='image' src='display.php?id=". $imgData['id'] . "' ></div>"; 
	  }
?>
</div>
dynamically-display-images-in-image-slider-using-php-and-mysql

FIle 'slider.php' requires 'display.php' to display images. It has following instructions.

Display.php

<?php
if(!empty($_GET[‘id’])){
    
    //Create connection and select DB
    $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
    
    //Check connection
    if($db->connect_error){
       die("Connection failed: " . $db->connect_error);
    }
    
    //Get image data from database
    $result = $db->query("SELECT image FROM images WHERE id = {$_GET['id']}");
    
    if($result->num_rows > 0){
        $imgData = $result->fetch_assoc();
        
        //Render image
        header("Content-type: image/jpg"); 
        echo $imgData['image']; 
    }else{
        //do nothing
    }
}
?>

when you run 'slider.php' file, the output will be displayed similar to following figure.

slider.php file displaying image in JSSOR slider from database

slider.php file displaying image in JSSOR slider from database

Source Code

Source code for this article is available here. It has following files. The file ‘dbconnect.php’ in source code contains settings for database. Please change it according to your server’s settings.

Source Code FIles

Source Code FIles

Comments

Satyendra singh yadav on March 21, 2020:

Thanks a lot

jean marie on September 20, 2019:

what we can replaceby data-u?

Timothy Malche (author) from Jabalpur, M.P., India on September 06, 2019:

good to hear.

jit bdr rana on August 28, 2019:

thank you so much ! .its helpful for me

Related Articles