1

I looked up some tutorials from youtube, like 5 of them but they're all not working for me for some reason, I'm only getting broken image icon.

I've tried using a folder to get the images like img src="images/$row['picture'];

But what I want is to display it straight from the database.

If possible please send me a code for it, so I will know if it's my browser or my coding.

I copied these codes but it's not even working

https://vikasmahajan.wordpress.com/2010/07/07/inserting-and-displaying-images-in-mysql-using-php/

It doesn't show the image:

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Otachan
  • 79
  • 1
  • 1
  • 8

1 Answers1

1

It is generally discouraged to approach it that way. <-(Good to know)

...it can still be done though and your use case may call for it...

With full credit to @Andomar:

First you create a MySQL table to store images, like for example:

create table testblob (
    image_id        tinyint(3)  not null default '0',
    image_type      varchar(25) not null default '',
    image           blob        not null,
    image_size      varchar(25) not null default '',
    image_ctgy      varchar(25) not null default '',
    image_name      varchar(50) not null default ''
);

Then you can write an image to the database like:

$imgData = file_get_contents($filename);
$size = getimagesize($filename);
mysql_connect("localhost", "$username", "$password");
mysql_select_db ("$dbname");
$sql = sprintf("INSERT INTO testblob
    (image_type, image, image_size, image_name)
    VALUES
    ('%s', '%s', '%d', '%s')",
    mysql_real_escape_string($size['mime']),
    mysql_real_escape_string($imgData),
    $size[3],
    mysql_real_escape_string($_FILES['userfile']['name'])
    );
mysql_query($sql);

You can display an image from the database in a web page with:

$link = mysql_connect("localhost", "username", "password");
mysql_select_db("testblob");
$sql = "SELECT image FROM testblob WHERE image_id=0";
$result = mysql_query("$sql");
header("Content-type: image/jpeg");
echo mysql_result($result, 0);
mysql_close($link);
Community
  • 1
  • 1
tinonetic
  • 7,751
  • 11
  • 54
  • 79
  • why is it discourage? because the project I'm working on right now is before the user uploads something the admin needs to verify it first and so the images will be displayed to the admin to verify it. And I dont want the uploaded images to go to the folder yet unless it is accepted by the admin – Otachan Sep 04 '16 at 08:51
  • Keyword is `generally`. You can read more on the link I posted. There are pros and cons to that approach. If your use case specifically requires that, then by all means do so. It's just good to know why one wouldnt use the approach too. – tinonetic Sep 04 '16 at 08:56
  • have you tried the code yourself? is it working? so I will know if the problem is in my browser or not – Otachan Sep 04 '16 at 13:05