Friday, 25 March 2016

Image Insertion, Display from Database in using PHP and MYSQL

Image Insertion, Display from Database in using PHP and MYSQL

You have worked with CURD operation on data. Images are just the same but there are few things you need to learn


Follow these steps one after another

Step1: Create a Database named as mytest

Step2: Create a table inside this db named as images

Add three columns inside this table

id int(100) Auto Increment
image blob(1000000)
name varchar(50)


Step3: Create a file named as connect_db.php

Paste the below code there and save the file. You need to update the host, username, password, database name according to you.


<?php
$host     ="localhost";
$user     ="root";
$pass     ="google";
$db     ="mytest";
?>

This file stores the credentials of your database.

Step4:  Create a file named as image_insert.php

Paste the below code and save the file

<html>
    <head>
        <title>Image File Insertion in Database</title>
    </head>
    <body>
        <h3>Please Choose a File and click Submit</h3>

        <form enctype="multipart/form-data" action=
            "<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
            <input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
            <input name="imagefile" type="file" />
            <input type="submit" value="Submit" />
        </form>
    </body>
</html>

<?php
// check if a file was submitted
if(!isset($_FILES['imagefile']))
{
    echo '<p>Please select a file</p>';
}
else
{
    try
    {
        $msg     = uploadImage();  //this function will upload your image
        echo $msg;  //Message showing success or failure.
    }
    catch(Exception $e)
    {
        echo $e->getMessage();
        echo 'Due to some problem, Could not upload file';
    }
}

// ******** The Image upload function ***************** //

function uploadImage()
{
    include "connect_db.php";
    $maxsize = 10000000; //set to approx 10 MB

    //check associated error code
    if($_FILES['imagefile']['error'] == UPLOAD_ERR_OK) {

        //check whether file is uploaded with HTTP POST
        if(is_uploaded_file($_FILES['imagefile']['tmp_name'])) {   

            //checks size of uploaded image on server side
            if( $_FILES['imagefile']['size'] < $maxsize) { 
 
               //checks whether uploaded file is of image type
              //if(strpos(mime_content_type($_FILES['imagefile']['tmp_name']),"image")===0) {
                 $finfo = finfo_open(FILEINFO_MIME_TYPE);
                if(strpos(finfo_file($finfo, $_FILES['imagefile']['tmp_name']),"image")===0) {   

                    // prepare the image for insertion
                    $imgData =addslashes (file_get_contents($_FILES['imagefile']['tmp_name']));

                    // put the image in the db...
                    // database connection
                    mysql_connect($host, $user, $pass) OR DIE (mysql_error());

                    // select the db
                    mysql_select_db ($db) OR DIE ("Unable to select db".mysql_error());

                    // our sql query
                    $sql = "INSERT INTO images
                    (image, name)
                    VALUES
                    ('{$imgData}', '{$_FILES['imagefile']['name']}');";

                    // insert the image
                    mysql_query($sql) or die("Error in Query: " . mysql_error());
                    $msg = '<p>Image successfully saved in database with id ='. mysql_insert_id().' </p>';
                }
                else
                    $msg = "<p>Uploaded file is not an image.</p>";
            }
             else {
                // if the file is not less than the maximum allowed, print an error
                $msg = '<div>File exceeds the Maximum File limit</div>
                <div>Maximum File limit is '.$maxsize.' bytes</div>
                <div>File '.$_FILES['imagefile']['name'].' is '.$_FILES['imagefile']['size'].
                ' bytes</div><hr />';
                }
        }
        else
            $msg = "File not uploaded successfully.";

    }
    else {
        $msg = file_upload_error_message($_FILES['imagefile']['error']);
    }
    return $msg;
}

// Function to return error message based on error code

function file_upload_error_message($error_code) {
    switch ($error_code) {
        case UPLOAD_ERR_INI_SIZE:
            return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
        case UPLOAD_ERR_FORM_SIZE:
            return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
        case UPLOAD_ERR_PARTIAL:
            return 'The uploaded file was only partially uploaded';
        case UPLOAD_ERR_NO_FILE:
            return 'No file was uploaded';
        case UPLOAD_ERR_NO_TMP_DIR:
            return 'Missing a temporary folder';
        case UPLOAD_ERR_CANT_WRITE:
            return 'Failed to write file to disk';
        case UPLOAD_ERR_EXTENSION:
            return 'File upload stopped by extension';
        default:
            return 'Unknown upload error';
    }
}
?>
</body>
</html>


Step5: Create a file named as file_display.php

<?php
 include "connect_db.php";
 // just so we know it is broken
 error_reporting(E_ALL);
 // some basic sanity checks
 if(isset($_GET['id']) && is_numeric($_GET['id']))
 {
     //connect to the database
     $conn = mysql_connect("$host", "$user", "$pass")
     or die("Could not connect: " . mysql_error());

     // select our database
     mysql_select_db("$db") or die(mysql_error());

     // get the image from the database
     $sql = "SELECT image FROM images WHERE id=" .$_GET['id'] . ";";

     // the result of the query
     $result = mysql_query("$sql") or die("Invalid query: " . mysql_error());

     // set the header for the image
     header("Content-type: image/jpeg");
     echo mysql_result($result, 0);

     // close the db connection
     mysql_close($conn);
 }
 else
 {
     echo 'Please use a numeric id number';
 }
?>

Step6: Open file Stored inside the database 

http://{path_to_your_web_directory}/file_display.php?id=1

For example:http://localhost/myFolder/file_display.php?id=1

Here id is the row id of the table
 

1 comment:

  1. i have created a separate field in the database called id. But when am uploading the images, the id is 0 for all the insertions. should i make it increment? if yes then how can i do that? please help me out.

    ReplyDelete