Popup modal with JS and PHP query

I’ve got a gallery where I have some buttons to filter the images by category. When you click an image it pops up a modal and shows the picture. It works when I open it up (at first it shows all the images) and when I choose a option 2021, but with other options it does not work. The strange thing is that when I click an image from (for example) option 2020, the modal does not show up, but when I click option 2021 the modal with the right picture shows up.
The buttons look like this:

<button data-filter=".2020">2020</button>
<button data-filter=".2021">2021</button>

I read the picture’s names from mysql database and shows it with a while loop with php.

query starts
echo '<div class="col-lg-3 col-md-6 special-grid '; echo $row["category"];  echo '">
...
<img id="myImg'; echo $db; $db++; echo'" src="gallery/'; echo $row["picturename"]; 
echo'" class="img-fluid" alt="Image" width="480" height="380">
query ends

Modal:

<div id="myModal" class="modal">
<span class="close">&times;</span>
<img class="modal-content" id="img01">
<div id="caption"></div>
</div>

Javascript:

<script>
var modal = document.getElementById("myModal");
var modalImg = document.getElementById("img01");
for (let i = 0; i < <?php echo $sizeofgallery ?>; i++) {
// Get the image and insert it inside the modal
   var img = document.getElementById("myImg" + i);
   img.onclick = function () {
       modal.style.display = "block";
       modalImg.src = this.src;
   }
}
var span = document.getElementsByClassName("close")[0];
span.onclick = function () {
   modal.style.display = "none";
}

</script>