joshua
joshua

Reputation: 177

How to store image of fixed size in MySQL using PHP?

I am trying to store an image from a user in the database but after insertion it is always showing the size of an image as 26B even if the image size was in Kb. I have taken longBlob in MySQL for storing the same. here is my code

<input type="file"  name="profile_picture" id="imgupload"  accept=".jpg,.png,.jpeg">


// for uploading image
   $ff_NAME = $_FILES['profile_picture']['name'];
   $ff_TMP_NAME = $_FILES['profile_picture']['tmp_name'];
   $ff_SIZE = $_FILES['profile_picture']['size'];
   $ff_ERROR = $_FILES['profile_picture']['error'];
   $ff_TYPE = $_FILES['profile_picture']['type'];

   $ffileExt = explode('.',$ff_NAME);
   $ffileActualExtention = strtolower(end($ffileExt));
   $fallowed = array('png','jpeg','jpg');

   if(in_array($ffileActualExtention,$fallowed))
   {
       if($ff_ERROR===0)
       {  
           if($ff_SIZE<500000)
           {
               $ffileNameNew = uniqid('',true)."".$ffileActualExtention;
               $ffileDestination = 'profileuploads/'.$ffileNameNew;
               move_uploaded_file($ff_TMP_NAME,$ffileDestination);
           }
           else
           {
               echo 'File size must be less than 500 kb.';
           }
       }
       else
       {echo "Error in uploading the files";}
   }
   else
   {echo "Only 'png','jpeg','jpg' are allowed";}

Insert query declaration:

  $query = "INSERT INTO detail (`f_profile_picture`) VALUES (?)";
   $stmtt = $conn->prepare($query);//prepared statement method 
   $stmtt->bind_param("s",$ffileNameNew);//binding a parameter to question mark
$stmtt->execute();
   if($stmtt->affected_rows > 0)
     {
     echo("success");
     }

     else
      {
     echo("failed");
     }

Upvotes: 0

Views: 255

Answers (1)

Gavin Kwok
Gavin Kwok

Reputation: 108

  1. move_uploaded_file($ff_TMP_NAME,$ffileDestination) means put uploaded file in your file system of path $ffileDestination
  2. $stmtt->bind_param("s",$ffileNameNew) here you are binding the saved filename
  3. when $stmtt->execute(), the filename is stored in database

now you are trying to show the image right?

  1. select out the stored filename in database
  2. get the path of this image which is stored in your file system
  3. show the image

when you show the image, there are basically two ways:

  1. the file is public, which means you can get the image from url like http://example.com/xxx.png. you can simply use <img src='http://example.com/xxx.png'>
  2. the file is private, you should use php to read the file content and render it out. (base64_encode may help)

Upvotes: 1

Related Questions