PHP Responsive Image Gallery using CSS Media Queries

Last modified on April 16th, 2018 by Vincy.

Gallery is a great way to showcase data in a grid view so that its appealing to the users. Its one of the nicest way to present your products. Your gallery can contain image, video or a collection of text data in a card. In the last post, I have created a gallery to show a card-like list page for a CRUD system. Displaying voluminous data in a gallery has the advantages of allowing the user to have a quick glance at the content.

image-gallery-view

View Demo

In this example, I have stored the gallery images in a folder. I have created a database table to store the physical location path of the images. Then I read the image location URL from the database table and iterate the result to display the image gallery. This gallery will be responsive and will fit into any device viewport seamlessly. I used CSS media queries to make the gallery responsive.

Read Gallery Images from the Database

The following code is used to fetch the image location path from the MySQL database table. The resultant array of database result will be iterated in a loop to display the images in gallery view. This code shows the HTML code for the gallery grid to display the images. If there is no such image file as read from the database, then I have shown a default image. I used PHP file_exists() function to check the existence of the physical location of the image.

<?php
include 'DBController.php';
$db_handle = new DBController();
?>
<!DOCTYPE html>
<html>

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

<body>

    <div id="gridview">
        <div class="heading">Image Gallery</div>
<?php
$query = $db_handle->runQuery("SELECT * FROM tbl_image ORDER BY id ASC");
if (! empty($query)) {
    foreach ($query as $key => $value) {
        ?>  
            <div class="image">
            <?php 
                if(file_exists($query[$key]["path"])) 
                { 
            ?>
            <img src="<?php echo $query[$key]["path"] ; ?>" />
            <?php 
                } else { 
            ?>
            <img src="gallery/default.jpeg" />
            <?php
                }
            ?>
            </div>
<?php
    }
}
?>
    </div>
</body>
</html>

CSS Media Queries for Creating Responsive Image Gallery

In this simple example, we can get clear about how the media queries are used in creating responsive views. In the following CSS, the image width is changed based on the viewport size by adding the range based styles. The range specification is for setting the min-max viewport screen size.

#gridview {
   text-align:center; 
}

div.image {
    margin: 10px;
    display: inline-block;
}

div.image img {
    width: 100%;
    height: auto;
    border: 1px solid #ccc;
}

div.image img:hover {
    box-shadow: 0 5px 5px 0 rgba(0,0,0,0.32), 0 0 0 0px rgba(0,0,0,0.16);
}

.heading{    
    padding: 10px 10px;
    border-radius: 2px;
    color: #FFF;
    background: #6aadf1;
    margin-bottom:10px;
    font-size: 1.5em;
}
#grid{
    margin-bottom:30px;
}

/* Responsive Styles */

@media screen and (min-width: 1224px) {
    div.image {
        width: 300px;
    }
}

@media screen and (min-width: 1044px) and (max-width: 1224px) {
    div.image {
        width: 250px;
    }
}

@media screen and (min-width: 845px) and (max-width: 1044px) {
    div.image {
        width: 200px;
    }
}

DBController Class to Establish Database Connection and Fetch Images

This DBController class establishes connection in its constructor. It contains function runQuery() to fetch database result by executing the query passed as its argument.

<?php
class DBController {
	private $host = "localhost";
	private $user = "root";
	private $password = "test";
	private $database = "phpsamples";
	private $conn;
	
        function __construct() {
        $this->conn = $this->connectDB();
	}	
	function connectDB() {
		$conn = mysqli_connect($this->host,$this->user,$this->password,$this->database);
		return $conn;
	}
    function runQuery($query) {
                $result = mysqli_query($this->conn,$query);
                while($row=mysqli_fetch_assoc($result)) {
                $resultset[] = $row;
                }		
                if(!empty($resultset))
                return $resultset;
	}
}
?>

MySQL DatabaseTable tbl_image Structure and Data

This this the SQL script for the tbl_image table data, structure and the indexes.

--
-- Table structure for table `tbl_image`
--

CREATE TABLE `tbl_image` (
  `id` int(8) NOT NULL,
  `name` varchar(255) NOT NULL,
  `path` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_image`
--

INSERT INTO `tbl_image` (`id`, `name`, `path`) VALUES
(1, 'Nature', 'gallery/photo1.jpeg'),
(2, 'water', 'gallery/photo8.jpeg'),
(3, 'water', 'gallery/photo2.jpeg'),
(4, 'sunny', 'gallery/photo3.jpeg'),
(5, 'Air', 'gallery/photo4.jpeg'),
(6, 'water', 'gallery/image9.jpg'),
(7, 'water', 'gallery/photo5.jpeg'),
(8, 'water', 'gallery/photo7.jpeg'),
(9, 'water', 'gallery/photo6.jpeg');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_image`
--
ALTER TABLE `tbl_image`
  ADD PRIMARY KEY (`id`);
COMMIT;

Simple Image Gallery using PHP – Output

This screenshot shows the image gallery output in desktop view and mobile view

Desktop View

php-responsive-image-gallery-output

Mobile View

php-responsive-image-gallery-output-mobile-view

View DemoDownload

This PHP code tutorial was published on April 13, 2018.

↑ Back to Top

Share this Article