Sunday, December 14, 2014

HOW TO STORE IMAGE IN MYSQL DATABASE FROM PHP

My previous post of the same topic was rather too easy. But how do we do it using some programming say PHP?. so lets start...

<!DOCTYPE HTML> 

<?php
   $db_host = "localhost";
   $db_username = "root";
   $db_pass = "usbw";
   $db_name = "image";
?>
<html>
<head>
</head>
<body>

<form> name="Image" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>"              method="POST"> 
         <center><fieldSet style="width:50%">
                        <p><input type="file" name="Photo" size="2000000"        
                         accept="image/gif, image/jpeg, image/x-ms-bmp, image/x-png" size="26"></p>
                        <input type="submit" name="submit" value="Upload image" size="50"> 
        </fieldSet></center>
</form>

$uploadDir='images/'; //image upload folder

if(isset($_POST['submit'])) {
   $fileName = $_FILES['Photo']['name'];
   $tmpName  = $_FILES['Photo']['tmp_name'];
   $fileSize = $_FILES['Photo']['size'];
   $fileType = $_FILES['Photo']['type'];
   $filePath = $uploadDir . $fileName;
   $result = move_uploaded_file($tmpName, $filePath);
   
   if (!$result) {
      echo "Error uploading file";
   exit; 
   }
   
   if(!get_magic_quotes_gpc()) {
       $fileName = addslashes($fileName);
       $filePath = addslashes($filePath); 
   }

   @mysql_connect ("$db_host", "$db_username", "$db_pass") or die ("Could not connect to 
       MySQL");
   @mysql_select_db("$db_name") or die ("No database");
   @mysql_query(" INSERT INTO `img`(`path`) VALUES ('$filePath')"); 

   echo '<script>alert("Image is successfully uploaded");</script>';
} 
else {
   echo "Complete the form before submitting";
}
?>
</body>
</html>

This is how it looks like on PHP page



Testing our codes:

1) upload new image [canary.jpg] : 


2) recheck your database to see if the image is successfully uploaded or not. (im my case, YEA! it works)



 SO WE ONLY FINISH THE FIRST STEP. LETS HIT THE NEXT ONE


No comments:

Post a Comment