Store image in mysql database using php

Step 1 :
  
Create Table to Store Image



/ImageTable.php

<?php

$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'mydb';

$con = mysqli_connect($host, $user, $pass, $db);
if(!$con){
    die('Connection Error!');
}

$sql = "create table image (id int not null auto_increment,"
        . "name varchar(30),"
        . "img longblob,"
        . "primary key(id))";

$result = mysqli_query($con, $sql);

if($result){
    echo 'Table created successfully';
}else{
    echo 'Table Already Exist!';
}


Step 2 : HTML Form

StoreImageForm.html preview




StoreImageForm.html

<!DOCTYPE html>
<html>
    <head>
        <title>Store Image Form</title>
    </head>
    <body>
        <h1>Store Image Form [ali-mirza.blogspot.com]</h1>
        <form action="SaveImage.php" method="post" enctype="multipart/form-data">
            Image Name : <input type="text" name="imgName" required><br>
            Image : <input type="file" name="img" required><br>
            <input type="submit">
        </form>
    </body>
</html>


Step 3 :

SaveImage.php preview


SaveImage.php preview

<?php
// SaveImage.php

$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'mydb';

$con = mysqli_connect($host, $user, $pass, $db);
if(!$con){
    die('Connection Error!');
}

if(isset($_POST['imgName'],$_FILES['img']['tmp_name'])){
    $imgName = $_POST['imgName'];
    $imgType = $_FILES['img']['name'];
    $imgType = end(explode('.', $imgType));
    if($imgType != "jpg"){
        die('Select only .jpg file!');
    }
    $imgSize = $_FILES['img']['size'];
    if($imgSize > 1000000){
        die('Select less then 1 MB');
    }
    $img = $_FILES['img']['tmp_name'];
    $img = file_get_contents($img);
    $img = addslashes($img);
    $sql = "insert into image (name,img) values ('$imgName','$img')";
    $result = mysqli_query($con, $sql);
    if($result){
        echo 'Image Save successfully';
    }else{
        echo 'Image Not Save';
    }
}
else
{
  echo 'Post Error!';  
}

No comments:

Post a Comment