How can PHP be used to filter and display database entries based on categories using buttons for user interaction?
To filter and display database entries based on categories using buttons for user interaction, you can create a PHP script that dynamically generates buttons for each category and then fetches and displays entries based on the selected category. This can be achieved by using SQL queries with WHERE clauses to filter entries based on the selected category.
<?php
// Connect to your database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch categories from database
$sql = "SELECT DISTINCT category FROM entries";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<button onclick='filterEntries(\"" . $row['category'] . "\")'>" . $row['category'] . "</button>";
}
}
// Fetch and display entries based on selected category
if(isset($_GET['category'])) {
$category = $_GET['category'];
$sql = "SELECT * FROM entries WHERE category = '$category'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row['entry_title'] . "<br>";
echo $row['entry_content'] . "<br><br>";
}
} else {
echo "No entries found for this category.";
}
}
$conn->close();
?>
Keywords
Related Questions
- Are there any best practices for handling undefined variables in PHP to prevent errors like the one mentioned in the forum thread?
- What are the best practices for displaying and managing assigned and unassigned customers in a selectbox in PHP?
- How can CSS compatibility issues be addressed when implementing PHP code for web applications?