How can PHP be used to read files from a database and display them in different formats?

To read files from a database and display them in different formats using PHP, you can retrieve the file data from the database, determine the file type, and then display it accordingly. You can use PHP's file handling functions to read the file data and output it in the desired format, such as displaying an image file as an image or a text file as text.

// Assume $db is the database connection

// Retrieve file data from the database
$query = "SELECT file_data, file_type FROM files WHERE id = 1";
$result = mysqli_query($db, $query);
$row = mysqli_fetch_assoc($result);

// Determine the file type
$fileType = $row['file_type'];

// Display the file data in the appropriate format
if ($fileType === 'image/jpeg' || $fileType === 'image/png') {
    header('Content-Type: ' . $fileType);
    echo $row['file_data'];
} elseif ($fileType === 'text/plain') {
    echo $row['file_data'];
} else {
    echo 'Unsupported file type';
}