Monday 20 August 2012

HOW TO insert and retrive an image into databse using PHP,MYSQL

// siddhu vydyabhushana // Leave a Comment
hello friends good morning am here with a extordinary coding , i know u all are aware about this, inserting and retriving an image into database mysql using php,

please save this file as index.php
<html>
<head>
</head>
<body>
<form name="myform" method="POST" action="index.php" enctype="multipart/form-data">
<input type='file' name='image'>
<input type='submit' name='upload'>
</form>
</body>

</html>

<?php

mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("dream") or die(mysql_error());


$file=$_FILES['image']['tmp_name'];

if(!isset($file))

echo "please select an image";

else
{
$image=addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name=addslashes($_FILES['image']['name']);
$image_size=getimagesize($_FILES['image']['tmp_name']);

if($image_size==FALSE)

echo "that is not an image";

else
{
if(!$insert=mysql_query("INSERT INTO store VALUES('','$image_name','$image')"))
echo "problem uploading image";
else
{
$lastid=mysql_insert_id();
echo "image uploaded.<p/>Your image:<p/> <img src='get.php?id=$lastid'></img>";
}

}
}
?>

please save the below file as get.php

<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("dream") or die(mysql_error());

$id=addslashes($_REQUEST['id']);

$image=mysql_query("SELECT * FROM store WHERE id=$id");
$image=mysql_fetch_array($image);
$image=$image['image'];

//header("Content-type:image/jpeg");

echo $image;
?>

please create a mysql table like below with name store


CREATE TABLE IF NOT EXISTS `store` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`image` blob NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

0 comments:

Post a Comment