Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load file from mysql with PHP

Tags:

file

php

mysql

I store images in my mysql database as blob. I can load these files with a query in a variable, but how can I send back the contents of this variable to the browser as an image?

Can the html file contain something like this <img src="smtg.png"> ? Or how the request can be made?

like image 235
Infinite Possibilities Avatar asked Jul 20 '11 14:07

Infinite Possibilities


People also ask

How do you load a file in MySQL?

mysql> LOAD DATA LOCAL INFILE '/path/pet. txt' INTO TABLE pet; If you created the file on Windows with an editor that uses \r\n as a line terminator, you should use this statement instead: mysql> LOAD DATA LOCAL INFILE '/path/pet.


2 Answers

You need a script that echos out the image data. Use header() to set the appropriate content type, and then echo the data. For example:

header("Content-type: image/png");
...
echo $db_results['imgdata'];

Then, call your script from the HTML page like this:

<img src="yourimagescript.php" />

Ideally, you should be storing file type in a column next to your image data, so you can dynamically set the correct content type.

like image 158
Brad Avatar answered Sep 19 '22 01:09

Brad


PHP

<?php
mysql_connect("localhost","test","test");
mysql_select_db("test");
$imageid = (int)$_GET['imgid'];
$rs = mysql_query("select * from images where imageid=$imageid");
$row = mysql_fetch_assoc($rs);
$imagebytes = $row['imgdata'];
header("Content-type: image/jpeg");
print $imagebytes;
?>

HTML

<img src="location_to_your_php_script.php?imgid=21" alt="xxx" />
like image 42
Senad Meškin Avatar answered Sep 21 '22 01:09

Senad Meškin