PHP, MySQL, Drupal, .htaccess, Robots.txt, Phponwebsites: Upload images to mysql database using php

30 Oct 2014

Upload images to mysql database using php

                         In this method, You won't need to store images in mysql database. Just store image name in mysql database and store image in particular directory. Then you can retrieve image from particular directory using image name in database. You can done it using php.

Create table using mysql query:


                create table image(
                     no int(4) AUTO_INCREMENT, img_name varchar(30), 
                     PRIMARY KEY(no) )
Now the table 'image' is created. Then you can store values to mysql database using php.

Upload images using php and mysql:


                  The php script for upload images to mysql database is:


<html>
<body>
<form action="#" method="post" enctype="multipart/form-data">
File: <input type="file" name="file">
       <input type="submit" name="submit" value="Upload">
</form>
<?php
 if(isset($_POST['submit']))
 { 
   mysql_connect('localhost','root','');
   mysql_select_db('new');
   $name=$_FILES['file']['name'];
   $type=$_FILES['file']['type'];
   if($type=='image/jpeg' || $type=='image/png' || $type=='image/gif' || $type=='image/pjpeg')
   {
if(file_exists(dirname($_SERVER['DOCUMENT_ROOT']).'/oops/upload/image/'.$name))
     {
      echo'file is already present';
     }
     else
     {
      $up=move_uploaded_file($_FILES['file']['tmp_name'],dirname($_SERVER['DOCUMENT_ROOT']).'/oops/upload/image/'.$name);
      $q=mysql_query("insert into image values('','".$name."')");
  if($up && $q)
  {
   echo'image uploaded and stored';
  }
  elseif(!$up) 
  {
   echo'image not uploaded';
  }
  elseif(!$q)
  {
   echo'image not stored';
  }
 }
   }
   else
   {
    echo'Invalid file type';
   }
 }
?>
</body>
</html>


        where,
                   $_FILES['file']['type'] is used to return the type of uploaded file.
                   move_uploaded_file() is used to upload the file.
You want to know about upload files in php.
                    if($type=='image/jpeg' || $type=='image/png' || $type=='image/gif' || $type=='image/pjpeg' ) is used to check the file type whether it is image or not. If it is image, then it is stored. Otherwise, it is not upload and also stored.
                   Now you can see the directory, the image is stored here and also stored in mysql database.

2 comments:

  1. Your tutorials are really helpful -
    Please continue with php tutorials

    ReplyDelete
  2. plese help me to retify this error
    Parse error: syntax error, unexpected 'file' (T_STRING) in C:\xampp\htdocs\p\img.php on line 13

    ReplyDelete