Upload Image to MySQL using PHP
As a new-bie to php/mysql, I tried different stuffs. So here I’m with my php code for Image Upload to MySQL. Its a quite simple code with two php files one to display and one to upload.
For Image Upload code, I’ve added code download link upload-image-mysql-demo.zip at the end of the page.
CREATE TABLE `pix` (
`pic_id` int(11) NOT NULL auto_increment,
`pic_name` varchar(100) NOT NULL,
`pic_data` longblob NOT NULL,
PRIMARY KEY (`pic_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Save images to MySQL using PHP
/* Image.php*/
<?php
$con = mysql_connect("127.0.0.1:3306","root","");
if (!$con)
{
die("Could not connect: " . mysql_error());
}
$DB = mysql_select_db("test", $con);
move_uploaded_file($_FILES["uploadedfile"]["tmp_name"],"latest.img");
$instr = fopen("latest.img","rb");
$image = addslashes(fread(fopen("latest.img","r"),filesize("latest.img")));
mysql_query ("insert into pix (pic_name, pic_data) values ("myImage", "'.$image.'");");
?>
<html>
<form enctype="multipart/form-data" method="POST">
<img src=showImage.php?gim=1 width=500 height=150 alt="hell">
<br><hr>
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload(<100 KB): <input name="uploadedfile" type="file" /><br/>
<input type="submit" value="submit" name="submit" />
</form>
<html>
Show image in MySQL using PHP
/*showImage.php*/
<?php
$con = mysql_connect("127.0.0.1:3306","root","");
if (!$con)
{
die("Could not connect: " . mysql_error());
}
$DB = mysql_select_db("test", $con);
$res = @mysql_query("select * from pix order by pic_id desc limit 1");
if ($row = @mysql_fetch_assoc($res))
{
$title = htmlspecialchars($row[pic_name]);
$bytes = $row[pic_data];
}
header("Content-type: image/jpg");
print $bytes;
mysql_close();
?>
Click here to download zip file for above demo of Uploading image to mysql using php.