PHP Scripts

Embed a JPG image in a MySQL database

The easiest way to deal with images is to store just the path in a database, and have the images online.

However, there are occassions when it's necessary to store the JPG as a blob in the database itself.
This simple script does that.

Let's assume you have a database, with a table called 'pix'
The table needs 4 fields or columns:
id: int(11), Primary, auto-increment
pics: blob
ext: varchar(4)
name: varchar(50)

The useage is:
insertpix.php?n=thumbname, eg, insertpix.php?n=1212

The include "conn.php" is a standard connect to your database with name, password etc.
Copy the code below and call it insertpix.php


<?php

$newimg=$_GET["n"];
echo "Embedding<br>$newimg<br>";
include "conn.php";

$handle = fopen("thumbs/$newimg.jpg", "rb");
$img = fread($handle, filesize("thumbs/$newimg.jpg"));
fclose($handle);
$img = base64_encode($img);

$sql = "insert into pix values(null,'$img','jpg','$newimg')";
mysql_query($sql) or die('Error Embedding');

echo "<br>$newimg embedded";

?>



Retrieve the JPG from MySQL

Back