How to save image to database in PHP



How to upload files(Images / Documents/) to Web pages in PHP ?

This tutorial will show you how to save image to a MySQL database using PHP.

To save an image into database, you need to define a table column as BLOB data type in MySQL
MySQL Query:

Create Database Mydb;
use Mydb;
create table images(sno integer auto_increment primary key,
imgname varchar(20) not null,
thumnail BLOB);

imageform.html

<html><head><title>Storing Uploaded image to Database</title></head>
 <body><form action="uploadimage.php" method="post" enctype="multipart/form-data">
<p>Select Image file<input type=file name="f1" />
<p><input type=submit value="Upload" />
 </form>
</body>
</html>

uploadimage.php

<?php
   
try
  {
   $loc='./images/'.$_FILES['f1']['name'];     
   $res=move_uploaded_file($_FILES['f1']['tmp_name'],$loc);
    if($res)
     echo $_FILES['f1']['name'].' File Uploaded successfuly';     
    else
     {
      echo $_FILES['f1']['name'].' File Not Uploaded. Try again';
      exit(1);
     }

  $name=$_FILES['f1']['name'];  
  $fdata=addslashes(file_get_contents($loc));
    $cn=mysql_connect("localhost","root");  
    mysql_select_db("Internet",$cn);
    $query="Insert into images(imgname,thumnail) values('".$name."','".$fdata."')";

    $res=mysql_query($query);
       if($res)
       {
        echo "<h3>Thanks! Image saved to Database</h3>";
        
       }
      else
       {
        echo "<h3>Error! Try again</h3>";
        include_once("imageform.html");
       }
    
  }
 catch(Exception $e)
  {
   echo 'OOPS!'.$e->getMessage();
  }

?>




Coming Soon:
How to read an image from a database using PHP and display it in a Web page?

2 comments:

  1. Awesome post. Here’s a tool that lets your build your online database without programming. There is no need to hand code PHP. Cut your development time by 90%
    http://www.caspio.com/

    ReplyDelete
  2. i want how to read an images from database using php plz update
    the code

    ReplyDelete

Thanks for visiting my Blog!

Have a Question ? Need Help in College Assignments, Need Code that is not available here? Just leave a comment & get your code instantly.

Tips to Enhance Your Blog