Tuesday, September 24, 2013

Store An Image In mysql Database PHP

Hey coders....
In this post I'll be showing you how to store a picture inside mysql databse.

1) Create the table as shown in the picture below...
  
 

2) Create database connection file.

db_connection.php
_______________________________________________________________________________

<?php
       
        $dbhost="localhost";
        $dbuser="root";
        $dbpass="test123"; 
        $dbdb="test";      //this is database name

        //conect to mysql
        $connect = mysql_connect($dbhost,$dbuser,$dbpass);
        if (!$connect)
        {
            echo "Failed To Connect To MySql".mysql_error();
        }

        //select database
        $db = mysql_select_db($dbdb,$connect);
        if (!$db)
        {
            echo "Failed To Connect To The Database".mysql_error();
        }

?>
_______________________________________________________________________________

3) Create UploadPic.php

newly added lines shown in blue.

UploadPic.php
 _______________________________________________________________________________
 <?php
include_once("db_connection.php"); //include the earlier created database connection file
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Upload Picture</title>
</head>

<body>
<form enctype="multipart/form-data" action="UploadPic.php" method="post">
     <input name="imageFile" type="file" size="35" >  <!--file type input-->
     <input type="submit" value="Upload">
</form>

<br>

</body>
</html>



_______________________________________________________________________________
 3) In between break and end-body tags of the above code...
................
................
</form>
<br>
 <!--here add these below lines of code-->
</body>
____________________________________________________________________________
<?php
//['tmp_name'] is accessing the temporary file name property of file type inputs
if(!isset( $_FILES['imageFile']['tmp_name'] )) // if not set
{
    echo "Select a picture";
}
else
{
    // file_get_contents() a built in function to get the content
    $pic = addslashes(file_get_contents($_FILES['imageFile']['tmp_name']) ); //addslashes() to prevent sql injection since we are storing this value to the database
    $pic_name = addslashes($_FILES['imageFile']['name']); //['name'] is accessing the name property of file type inputs
   
    $pic_size = getimagesize($_FILES['imageFile']['tmp_name']);
   
    if($pic_size == FALSE)
    {
        echo "Invalid! That is not an image...";
    }
    else
    {
        $sql = "INSERT INTO pic VALUES('','".$pic_name."','".$pic."')"; //here 'pic' is the table created  can leave first column(id) value empty since it's auto generated
        $queryResult = mysql_query($sql);
      
        //check if sql qury properly executed
        if(!$queryResult)
        {
            echo "Ooops! There was a problem uploading the picture";
        }
        else
        {
            $lastId = mysql_insert_id(); //returns the lastly inserted record id
            echo "Yahooo Image uploaded...";
            echo "<br>";
            echo "<img src=getPic.php?passedId=$lastId >";
          
        }
    }
}
   
?>
 _______________________________________________________________________________

 4) Now create getPic.php file

getPic.php

_______________________________________________________________________________

 <?php
include_once("db_connection.php");

$idVar = addslashes($_REQUEST['passedId']); //  $_REQUEST since we are requesting an id from an <img tag>
$sql = "SELECT * FROM pic WHERE id = $idVar " ;
$queryRes = mysql_query($sql);
$picture = mysql_fetch_array($queryRes);
$pic = $picture['image']; // in picture['image']  , 'image' is database column name

header("Content-type: image/jpeg");
echo $pic;

?>

_______________________________________________________________________________

 If still the picture is not displayed after clicking "Upload" button...

use the below line...
ob_clean();
before 
header("Content-type: image/jpeg"); line

Now it should work.... :)

Hope this helped....
Please leave a comment.
Suggestions for improvements are also welcomed :)

...Happy Coding...    



No comments:

Post a Comment