How can PHP be used to dynamically load and display products based on the selected category in a webshop system?
To dynamically load and display products based on the selected category in a webshop system, you can use PHP to fetch the products from a database based on the selected category ID. You can then loop through the fetched products and display them on the webpage.
<?php
// Assume $selectedCategoryId contains the selected category ID
// Connect to the database
$conn = new mysqli("localhost", "username", "password", "dbname");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch products based on the selected category ID
$sql = "SELECT * FROM products WHERE category_id = $selectedCategoryId";
$result = $conn->query($sql);
// Display products
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Product Name: " . $row["name"] . "<br>";
echo "Price: $" . $row["price"] . "<br><br>";
}
} else {
echo "No products found in this category.";
}
// Close database connection
$conn->close();
?>
Related questions
-
switch statement array dynamic page inclusion
-
Character encoding PHP scripts troubleshooting
-
MVC OOP security