user1849962
user1849962

Reputation: 1363

Displaying images from a mysql database

i am relatively new to php. I have a problem with displaying images in my browser ( google chrome) after retrieving blob data from mysql database.

Basically the following code works when the slashes are added in front of the echo at the bottom. However i have followed other online tutorials and the tutor has been able to display their images without the use of slashes whilst i am unable to get the image up. I just wondered what the standard rule is? Another thing to add - when i do fail to get the images up in the browser i get instead a ting thumbnail. I would really appreciate if anybody could tell me how to reliably display images. The site i wish to create is just about images. So its kind of fundamental. Thanks a lot in advance for your time.

<?php
$conn = mysql_connect ("localhost","root","arctic123");
$db = mysql_select_db ("user_images", $conn);

if(!$db) {
    echo mysql_error();
}

$q = "SELECT * FROM images";
$r = mysql_query ("$q",$conn);
if($r) {
    while($row = mysql_fetch_array($r)) {
        //echo $row ['username'];
        //echo "<br>";
        header ("Content-type: image/jpeg");
        echo $row ['logo'];
        //echo "<br>";
    }
}else{
    echo mysql_error();
}
?>

Upvotes: 1

Views: 1772

Answers (3)

joequincy
joequincy

Reputation: 1395

I would recommend not storing your images in a database. While it is technically possible, it has serious performance concerns. Best practice would be to designate a folder for the images, then access them directly. If you'd like the filtering and sorting ablities of MySQL, then replace the BLOB column that currently stores the image data with a VARCHAR containing the file name.

<?php
$conn = mysql_connect ("localhost","root","arctic123");
$db = mysql_select_db ("user_images", $conn);
$imgdir = "/path/to/image/directory/";

if(!$db) {
    echo mysql_error();
}

$q = "SELECT * FROM images";
$r = mysql_query ("$q",$conn);
if($r) {
    while($row = mysql_fetch_array($r)) {
        echo $row['username'];
        echo "<br>";
        echo "<img src='" . $imgdir . $row['logo'] . "' />";
        echo "<br>";
    }
}else{
    echo mysql_error();
}
?>

Upvotes: 0

Emmy Steven
Emmy Steven

Reputation: 143

Hope you are not storing your images on MySQL, please if you do, desist from that detrimental act because it is going to make your database unnecessarily heavy...

Upvotes: 0

tobiv
tobiv

Reputation: 842

You can't have header after any output in your code: http://php.net/manual/en/function.header.php

Best practice is to upload images to a directory and just store the image's path/file name in the database. Also makes it easier to manipulate the image, e.g. create different sizes and thumbnails with PHP. And it takes about four times less the disk space...

Upvotes: 2

Related Questions