Creating image-based filters using PHP and MySQL with clickable buttons

I’m working on a project where I need to create a filtering system using clickable image buttons. The setup involves several small image inputs that act as filter controls. When a user clicks on one of these images, I want my MySQL query to filter the results based on the selected category.

The functionality seems to be working as expected, but I keep getting PHP notices in my code. I’m not sure what’s causing these warnings or how to fix them properly.

Here’s my current implementation:

.filter-thumbs { height: 50px; display: inline-block; }
.gallery-display { height: 180px; }
<form action="" method="post">
  <input type="image" name="fedora" value="fedora" alt="fedora hat" src="example1.jpg" class="filter-thumbs">
  <input type="image" name="bowler" value="bowler" alt="bowler hat" src="example2.jpg" class="filter-thumbs">
</form>
<?php
$connection = mysqli_connect("localhost", "username", "password") or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($connection, "shop_db") or die("Database error: " . mysqli_error($connection));

if($_POST['fedora']) {
    $query_result = mysqli_query($connection, "SELECT * FROM accessories WHERE category='Fedoras'");
} elseif($_POST['bowler']) {
    $query_result = mysqli_query($connection, "SELECT * FROM accessories WHERE category='Bowlers'");
} else {
    $query_result = mysqli_query($connection, "SELECT * FROM accessories");
}

while($data = mysqli_fetch_array($query_result)) {
    echo "<img src='" . $data['item_image'] . "' class='gallery-display'>";
}
?>

What could be causing the PHP notices and how can I resolve them?

You’re seeing those notices because $_POST variables don’t exist when the page first loads. Wrap your if statements with isset() like if(isset($_POST['fedora'])) to check if they exist before using them. Also consider using prepared statements for better security.