Tuesday, January 22, 2013

Php image upload to mysql

Uploading image into mysql

First create table to upload image

create table poster(
id number(3) primary key AUTO_INCREMENT,
image longblob);

Now we shall write php script for inserting image into mysql database

<html>
<head>
<?php 
$username = "root";
$password = "";
$host = "localhost";
$database = "database";

$link = mysql_connect($host, $username, $password);
mysql_select_db ($database);
if(isset($_POST['submit']))
{
 $tmpName  = $_FILES['image']['tmp_name'];  
        
          // Read the file 
          $fp     = fopen($tmpName, 'r');
          $data = fread($fp, filesize($tmpName));
          $data = addslashes($data);
          fclose($fp);
 
 $sql="insert into poster (image) values ('$data')";
if (!mysql_query($sql,$link))
  {
  echo'Error';
  }
else
{
echo'Inserted Successfully';
}
}
?>
</head>
<body>
<form method="post" enctype="multipart/form-data" action="">
<input type="file" name="image" />
<input type="submit" name="submit" />
</form>
</body>
</html>

We inserted image into database, now we shall retrieve the image
<html>
<body>

<?php 
mysql_select_db($database, $link);
$result = mysql_query("SELECT * FROM poster");
while($row = mysql_fetch_array($result))
  {
 echo '<img class="eachrecipe" src="data:image/jpeg;base64,' . base64_encode( $row['image'] ) . '" height="200px" width="200px" border="0">';
  }
  mysql_close($link);  
?>

</body>
</html>

This completed the post.