PHP Responsive Image Gallery using CSS Media Queries

by Vincy. Last modified on July 25th, 2022.

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.

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.

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

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.

index.php

<?php
require_once __DIR__ . '/Connection.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/style.css" rel="stylesheet" type="text/css">
</head>
<body>
    <div id="gridview">
        <div class="heading">Image Gallery</div>
<?php
$sql = "SELECT * FROM tbl_image ORDER BY id ASC";
$statement = $conn->prepare($sql);

$statement->execute();
$result = $statement->get_result();

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        ?>
          <div class="image">
            <?php
        if (file_exists($row["path"])) {
            ?>
                <img src="<?php echo $row["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.

css/style.css

#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.

Config.php

<?php

class Config
{

    const HOST = 'localhost';

    const USERNAME = 'root';

    const PASSWORD = '';

    const DATABASENAME = 'image_responsive';
}
?>

Connection.php

<?php
require_once __DIR__ . '/Config.php';
$conn = new \mysqli(Config::HOST, Config::USERNAME, Config::PASSWORD, Config::DATABASENAME);
?>

MySQL DatabaseTable tbl_image Structure and Data

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

structure.sql

--
-- Database: `image_responsive`
--

-- --------------------------------------------------------

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

CREATE TABLE `tbl_image` (
  `id` int(8) NOT NULL,
  `name` varchar(255) NOT NULL,
  `path` text NOT NULL
);

--
-- 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`);

View DemoDownload

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “PHP Responsive Image Gallery using CSS Media Queries”

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page