I’m encountering an issue with passing query parameters from index.php to products.php in a simple PHP web application. Here’s the code I’m using:
index.php:
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="products.php?category=laptops">laptops</a></li>
<li><a class="dropdown-item" href="products.php?category=phones">phones</a></li>
</ul>
products.php:
<?php
if (isset($_GET['category'])) {
$selectedCategory = $_GET['category'];
echo "The category from the clicked link is: " . $selectedCategory;
} else {
echo "No category was passed.";
}
?>
The expected behavior is that when I click on a link in index.php, it should take me to products.php with the selected category as a query parameter, and products.php should display "The category from the clicked link is: [selectedCategory]" if the category query parameter is set, or "No category was passed" if it’s not set. Currently it always shows "No category was passed"
PHP appears to work properly because index.php has the following code which works without problems:
<?php
$servername = "localhost";
$username = "root";
$password = "Admin";
$database = "testdata";
$MK = "";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {die("Connection failed: " . $conn->connect_error);}
$sql = "SELECT * FROM product WHERE category = 'laptops'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$MK = $MK . "
<div class='col'>
<div class='card h-100'>
<div class='card-header text-capitalize'>" . $row["category"] . "</div>
<img src='img/testimg.png' class='card-img-top mt-3' alt='...'>
<div class='card-body'>
<h5 class='card-title mk-truncate-2'>" . $row["name"] . "</h5>
<div class=''><p class='mk-truncate-2'>" . $row["description"] . "</p></div>
</div>
<div class='card-footer p-0'>
<div class='row'>
<div class='col-sm pt-3'>€ " . $row["price"] . "</div>
<div class='col-sm border-start p-2'>
<small class='text-muted'>
<a href='#' class='btn btn-primary'>Buy</a>
</small>
</div>
</div>
</div>
</div>
</div>";
}
} else {
echo "No records found with category 'a'";
}
$conn->close();
?>
• I work in Visual Studio Code
• Both index.php and products.php are in the same directory.
What could be causing this issue, and how can I troubleshoot it?