I am retrieving an array of book objects with attributes like title,isbn and image. When I wish to display only labels using for loop it is displaying all entries. But when I try to display image, it only displays one. Also when I try to display both title and image, it says can
Warning: Cannot modify header information - headers already sent by (output started at /Applications/XAMPP/xamppfiles/htdocs/BookStore/BooksResult.php:14) in /Applications/XAMPP/xamppfiles/htdocs/BookStore/BooksResult.php on line 15.
Below is the code.
foreach($booksArr as &$book)
{
$content = $book->Image;
$title=$book->s_Title;
echo $title;
header('Content-type: image/jpg');
{
echo $content;
}
}
The “Cannot modify header information…” problem is here:
Your PHP script is outputting HTML. You cannot change the content type of the output mid-stream. Instead, you should output an
<img>tag that points to the image location.UPDATE BASED ON COMMENT DATA:
If you need to serve your images as blobs from the database, you will need to create a separate script to fetch the images. First modify this one to reference the new script by creating an
<img>tag with asrcattribute that contains the path to your image-fetching script and the image ID:Substitute
$row_idwith the field data that uniquely identifies a book in your database.Next, create the new image fetching script. It will contain three elements:
A line to get the
idfrom the GET request:$id = $_GET[‘id’];
An SQL statement to fetch the image blob based on the ID. (Remember to sanitize your input!)
A
header()statement like the one you used in your original scriptAfter the
header()line, just output the blob, and your image will be displayed.