How can PHP be used to generate and download files from a database?

To generate and download files from a database using PHP, you can retrieve the file data from the database, create a file on the server, and then prompt the user to download it. You can use PHP's file handling functions to achieve this.

<?php
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');

// Retrieve file data from the database
$stmt = $pdo->prepare("SELECT file_data, file_name FROM files WHERE id = :id");
$stmt->bindParam(':id', $_GET['file_id']);
$stmt->execute();
$file = $stmt->fetch();

// Create a file on the server
$file_path = 'downloads/' . $file['file_name'];
file_put_contents($file_path, $file['file_data']);

// Prompt the user to download the file
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $file['file_name'] . '"');
readfile($file_path);

// Delete the file from the server
unlink($file_path);
?>