How can PHP be used to dynamically filter and display database entries in a form?

To dynamically filter and display database entries in a form using PHP, you can create a form with input fields for filtering criteria (e.g., search term, category) and use PHP to query the database based on the submitted form data. You can then display the filtered database entries in a table or list format on the same page.

<?php
// Connect to 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);
}

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $searchTerm = $_POST['searchTerm'];
    $category = $_POST['category'];

    // Query database based on filter criteria
    $sql = "SELECT * FROM entries WHERE title LIKE '%$searchTerm%' AND category = '$category'";
    $result = $conn->query($sql);

    // Display filtered entries
    if ($result->num_rows > 0) {
        echo "<table>";
        while($row = $result->fetch_assoc()) {
            echo "<tr><td>" . $row["title"] . "</td><td>" . $row["category"] . "</td></tr>";
        }
        echo "</table>";
    } else {
        echo "No results found.";
    }
}
?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type="text" name="searchTerm" placeholder="Search term">
    <select name="category">
        <option value="category1">Category 1</option>
        <option value="category2">Category 2</option>
    </select>
    <button type="submit">Filter</button>
</form>