How can PHP be used to export data from a database based on user input, such as date range selection?

To export data from a database based on user input, such as date range selection, you can use PHP to create a form where users can input their desired date range. Then, use PHP to retrieve data from the database based on the user's input and generate a downloadable file, such as a CSV or Excel file, containing the exported data.

<?php
// Check if the form is submitted
if(isset($_POST['submit'])){
    // Get the start and end dates from the form
    $start_date = $_POST['start_date'];
    $end_date = $_POST['end_date'];

    // Query the database to retrieve data based on the date range
    // Replace 'your_query_here' with your actual SQL query
    $query = "SELECT * FROM your_table WHERE date BETWEEN '$start_date' AND '$end_date'";
    $result = mysqli_query($connection, $query);

    // Generate CSV file
    $filename = 'exported_data.csv';
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="'.$filename.'"');
    
    $output = fopen('php://output', 'w');
    fputcsv($output, array('Column 1', 'Column 2', 'Column 3')); // Add column headers

    while($row = mysqli_fetch_assoc($result)){
        fputcsv($output, $row);
    }
    fclose($output);
}
?>

<!-- Create a form for users to input date range -->
<form method="post">
    <label for="start_date">Start Date:</label>
    <input type="date" name="start_date" id="start_date" required>
    
    <label for="end_date">End Date:</label>
    <input type="date" name="end_date" id="end_date" required>
    
    <button type="submit" name="submit">Export Data</button>
</form>