Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To filter data through a dropdown in PHP, you can follow these steps:

  1. Set up a form with a dropdown that contains the options you'd like to filter the data by.
  2. When the form is submitted, retrieve the selected value from the dropdown using the $POST or $GET superglobals.
  3. Use the retrieved value to construct a SQL query that retrieves the relevant data based on the selected filter.
  4. Execute the SQL query and display the filtered data on the page.

Here is an example code snippet that demonstrates how to filter data through a dropdown in PHP:

// Set up a form with a dropdown that contains the filter options
echo '<form method="post">';
echo '<select name="filter">';
echo '<option value="">All</option>';
echo '<option value="option1">Option 1</option>';
echo '<option value="option2">Option 2</option>';
echo '</select>';
echo '<input type="submit" name="submit" value="Filter">';
echo '</form>';

// If the form is submitted, retrieve the selected filter value and construct a SQL query
if (isset($_POST['submit'])) {
    $filter = $_POST['filter'];
    $sql = "SELECT * FROM my_table";
    if (!empty($filter)) {
        $sql .= " WHERE column_name = '$filter'";
    }
    // Execute the SQL query and display the filtered data
    // ...
}

Note that you should always use prepared statements with parameter binding to prevent SQL injection attacks when constructing SQL queries.