I am trying to display image files stored in my mysql. It displays alright as a direct php echo, but when i put it in an <img.../> src attribute... I get a cross. The following is the code snippet;

...
$query = mysql_query("SELECT pid, imgdata FROM pix WHERE pid='2'");
    $row = mysql_fetch_array($query);
    $content = $row['imgdata'];
    header('Content-type: image/jpg');
    //echo $content;
?>

<html>
    <title>Sample Pix</title>
    <body>
        <table border="0" cellspacing="4" cellpadding="5">
            <tbody>
                <tr>
                <td><img src=$content width="200" height="170"/>
<!-- <img trial1 src=" echo $row['$content']; ?> trial2 echo $content;--></td>
                </tr>
            </tbody>
        </table>

    </body>
</html>

Any help that will help me display these images quickly in the attribute with the attribute measurement will be very appreciated very much.

Recommended Answers

All 3 Replies

You have an open " in the img src = "
but no closed quote.

Member Avatar for langsor

I am trying to display image files stored in my mysql. It displays alright as a direct php echo, but when i put it in an <img.../> src attribute... I get a cross.

I don't know what you mean by 'I get a cross', I usually get a ton of binary data written out to the screen when I try what you're doing and since I have had no luck writing the image header before the html data ... maybe I should play around with it some more?

What I do is make a separate PHP file to query the images data-table and print the header('Content-type: image/jpeg'); or whatever, followed by the raw binary data ... and call that PHP file as the src of the <img> tag ... with some identifier for what image to load.
<img src="images.php?image=3" />

But the challenge is, of course, getting the other attributes with only one sequel call to the images table ... so you have a couple options that I know of ...
1. Don't use the image attributes height,width, etc in the image tag.
2. Make multiple table queries for the rest of the image data.
3. Print a temp-image file to the server and either use the URL to that file, or get the image data from that file for the html image tag.
4. and probably the best option in most cases -- don't store image binary data in the database, just store the file-path to the image in the images directory and all associated image data in the database table. The is most efficient use of the DB too, from what I hear.

Cheers

No php tags on this line...

<img src=$content width="200" height="170"/>

You should try this:

<img src="<?php echo $content; ?>" width="200" height="170"/>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.