Tuesday, 28 August 2012

Saving and retrieving images using MySQL through PHP

I really should have looked into this a long time ago, but still. The example below deliberately doesn't use jQuery. If you want to POST files through jQuery, you'll need to use an ajax form plugin.

Right. Now we've got that out of the way, to my example. I have created a database in MySQL with a table called pictures, and I have 2 fields:
id : int(8)

picture : longblob
I have used the database class which I developed earlier to handle the requests.
At this stage, I'm just handling JPEG images.


<?php
require_once 'database.class.php';
$db = new database;
if($_POST)
{
$image=$_FILES['uploadfile']['tmp_name'];
$fp = fopen($image, 'r');
$content = fread($fp, filesize($image));
$content = addslashes($content);
fclose($fp);
$sql="insert into pictures (picture) values ('$content')";
$results = $db->query($sql);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File upload</title>
</head>
<body>
<form enctype="multipart/form-data" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
<input name="uploadfile" id="uploadfile" type="file" />
<input type="submit" value="Submit" />
</form>
<div id="results">
<?php
$arr = $db->query('SELECT * FROM pictures');
if($arr)
{
foreach($arr as $row)
{
echo $row['id'];
echo '<img src="data:image/jpeg;base64,'.base64_encode($row['picture']).'" /><br />';
}
}
?>
</div>
</body>
</html>

Enjoy!

No comments:

Post a Comment