Multiple CSS Modal Images on a single page with PHP
Tags: css, webdev, php, html
Published: 2019-12-13 05:34:18

If you've been wondering how to have more than one modal image on one page then this should be of help to you, with a little tweak of our css you can get your code running

After going through different solutions across the web on having more than one  modal image on page, i finally achieve this with the help of a php code.

Before proceeding you should be familiar with 'id' attributes, they are unique way of identifying HTML element on a page, the value can be use to perform certain task by calling it through CSS or javascript, in this tutorial we'll be getting our id from a php variable.

Below is the folder structure we'll be using, inside the image folder we'll create additional folders to hold single image file you can name this folder anything but make sure its a unique name: so i decide to use numbers

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/pxh81u6etd51h68s5979.png)

Note: the html, css, javascript is gotten from here [w3school](https://www.w3schools.com/howto/howto_css_modal_images.asp) we will setup the php path ourselve:

`connect.php` for database connection
```php
<?php 
$con = mysqli_connect("localhost", "root", "", "imagemodal");

if (!$con) {
    die("Connection failed: " .mysqli_connect_error());
}
?>
```
`imagetb.sql` which hold the table field and corresponding data:
```sql
-- Database: `imagemodal`
-- Table structure for table `imagetb`
CREATE TABLE `imagetb` (
  `imageId` int(11) NOT NULL AUTO_INCREMENT,
  `imageName` varchar(200) NOT NULL UNIQUE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- Dumping data for table `imagetb`
INSERT INTO `imagetb` (`imageId`, `imageName`) VALUES
(1, 'Chrysanthemum'),
(2, 'Lighthouse'),
(3, 'Desert'),
(4, 'Hydrangeas');

```
`header.php` for page hearder
```html
<!DOCTYPE html>
<html>
<head>
    <title>Multiple Modal Images on One Page</title>

    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0, user-scalable=no, maximum-scale=1.0, minimal-ui' />
	
    <style type='text/css'>
        body{
	    font-size: 16px;
            line-height: 1.5; 
	}  
    </style>
</head>
```

`modal.style.php` this hold our stylesheet which is here <a href="https://www.w3schools.com/howto/howto_css_modal_images.asp">w3School</a>

`index.php` our main file

*.First we will include the required file first
```php
<?php
include 'connect.php';
include 'header.php';
include 'modal.style.php';
?>
```
 
*. After including the required file, we will fetch the values from imagetb in our case we have only two that is `imageId` and `imageName`

```php
<?php
echo "<p>Multiple Modal Images on a Single page</p>";
$output1 = "SELECT * FROM imagetb";
$result1 = $con->query($output1) or die($con->error);
?>
```

*. We will fetch all our result row as an associative array into a while block and create two variables inside it, the `$imageId` in this case is an auto_incremented value from our db, that was the reason behind naming the individual folders in which our images will be placed with number
```php
<?php
echo "<div>";
	while ($row = $result1->fetch_assoc()) {

		$imageId = $row['imageId'];
		$imageName = $row['imageName'];
		
	}
	echo "</div>";
?>
```

*. Inside the while block and immediately after the two variables, we will create another variable which will point to the directory where our image files are and use a while block to open up all the folder inside the `images` folder
```php
<?php
echo "<div>";
		$dir = "images/".$imageId."/";
		$open = opendir($dir);

		while (($file = readdir($open)) != false) {
			if ($file != "." && $file != ".." && $file != "Thumbs.db") {
				echo"<img id='$imageId' src='$dir/$file' alt='$imageName' style='height:300px; width:200px; border-radius: 10%;'>
			            ";
			}
		}

		echo "<h4 style='text-align:center' id='".$imageId."'>".$imageName."</h4>";
?>
``` 

*.  Create a div tag immediately after the above while block which will hold our modal images when clicked
```php
<?php
echo "
			<!-- The Modal -->
		    <div id='myModal' class='modal'>
		        <span class='close'>&times;</span>
		        <img class='modal-content' id='img01' style='height:300px; width:200px; border-radius: 10%;'>
		        <div id='caption'></div>
		    </div>
		";
		echo "</div>";
?>
```

*. Create a script tag, immediately after the above div with the following content. So what happens is that whenever an image is clicked, it  will be collected with a unique id and inserted into the modal div. Basically the `var img = document.getElementById('$imageId');` is been changed when an image is clicked so it save us the id problem


```php
<?php
echo "
			<script>
		        // Get the modal
		        var modal = document.getElementById('myModal');

		        // Get the image and insert it inside the modal - use its 'alt' text as a caption
			    var img = document.getElementById('$imageId');
			    var modalImg = document.getElementById('img01');
			    var captionText = document.getElementById('caption');
			    img.onclick = function(){
			      	modal.style.display = 'block';
			        modalImg.src = this.src;
			        captionText.innerHTML = this.alt;
			    }

			    // Get the <span> element that closes the modal
			    var span = document.getElementsByClassName('close')[0];

			    // When the user clicks on <span> (x), close the modal
			    span.onclick = function() { 
			        modal.style.display = 'none';
			    }
		   	</script>
		";
?>
```

*. Here is the complete look of our index.php
```php
<?php  

	include 'connect.php';
	include 'header.php';
	include 'modal.style.php';
		
	echo "<p>Multiple Modal Images on a Single page</p>";
	$output1 = "SELECT * FROM imagetb";
	$result1 = $con->query($output1) or die($con->error);

	echo "<div>";
	while ($row = $result1->fetch_assoc()) {

		$imageId = $row['imageId'];
		$imageName = $row['imageName'];
		

		echo "<div>";
		$dir = "images/".$imageId."/";
		$open = opendir($dir);

		while (($file = readdir($open)) != false) {
			if ($file != "." && $file != ".." && $file != "Thumbs.db") {
				echo"<img id='$imageId' src='$dir/$file' alt='$imageName' style='height:300px; width:200px; border-radius: 10%;'>
			            ";
			}
		}

		echo "<h4 style='text-align:center' id='".$imageId."'>".$imageName."</h4>";
			
		echo "
			<!-- The Modal -->
		    <div id='myModal' class='modal'>
		        <span class='close'>&times;</span>
		        <img class='modal-content' id='img01' style='height:300px; width:200px; border-radius: 10%;'>
		        <div id='caption'></div>
		    </div>
		";
		echo "</div>";
		echo "
			<script>
		        // Get the modal
		        var modal = document.getElementById('myModal');

		        // Get the image and insert it inside the modal - use its 'alt' text as a caption
			    var img = document.getElementById('$imageId');
			    var modalImg = document.getElementById('img01');
			    var captionText = document.getElementById('caption');
			    img.onclick = function(){
			      	modal.style.display = 'block';
			        modalImg.src = this.src;
			        captionText.innerHTML = this.alt;
			    }

			    // Get the <span> element that closes the modal
			    var span = document.getElementsByClassName('close')[0];

			    // When the user clicks on <span> (x), close the modal
			    span.onclick = function() { 
			        modal.style.display = 'none';
			    }
		   	</script>
		";
	}
	echo "</div>";
?>
```

Here is where my post ends and wishing you  a better coding experience, the entire project can be clone from my github repo
{% github https://github.com/mdjibril/multiple-modal-image no-readme %}
. Happy Coding