Upload and Display image from database using php mysql | Sanwebcorner

Upload and Display image from database using php mysql

Hello , Now i am going to explain about how to upload the image to database table and how display those images in gallery page. first you have to create database in my sql ,Then you have to create two table one is login table and another one is output-image table for storing images. the structure of tables given below.

Step1: Create database named image

Database: `image`

Step2: Create login table using following mysql query.

CREATE TABLE IF NOT EXISTS `login` (
`id` int(10) NOT NULL,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `name` varchar(30) NOT NULL,
  `salt` varchar(30) NOT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

Step3: Dumping Data for login table:

INSERT INTO `login` (`id`, `username`, `password`, `name`, `salt`) VALUES
(1, 'admin', 'bsnl123', 'admin', '');

Stpe4: Create table ouput_images using following sqlquery:

CREATE TABLE IF NOT EXISTS `output_images` (
`imageId` tinyint(3) NOT NULL,
  `imageType` varchar(25) NOT NULL DEFAULT '',
  `imageData` mediumblob NOT NULL,
  `name` varchar(50) NOT NULL,
  `description` varchar(100) NOT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=88 ;


Now the backend process over , Then we can see how to upload images and display images from database using php

Step5:  imageUpload Page

upload image
image upload page

imageUpload.php:

<?php
if (count($_FILES) > 0) {
if (is_uploaded_file($_FILES['userImage']['tmp_name'])) {
mysql_connect("localhost", "root", "");
mysql_select_db("image");
$name = $_POST['name'];
//        $description = $_POST['description'];
$imgData = addslashes(file_get_contents($_FILES['userImage']['tmp_name']));
$imageProperties = getimageSize($_FILES['userImage']['tmp_name']);
$sql = "INSERT INTO output_images(imageType ,imageData,name)
VALUES('{$imageProperties['mime']}', '{$imgData}', '$name')";
$current_id = mysql_query($sql) or die("<b>Error:</b> Problem on Image Insert<br/>" . mysql_error());
if (isset($current_id)) {
header("Location: listImages.php");
}
}
}
?>
<html>
<head>
<title>San web tutorials</title>
<link href="css/vendor/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="js/vendor/jquery-1.8.3.min.js" type="text/javascript" ></script>
<script language="javascript">

(function ($) {
$.fn.checkFileType = function (options) {
var defaults = {
allowedExtensions: [],
success: function () {
},
error: function () {
}
};
options = $.extend(defaults, options);

return this.each(function () {

$(this).on('change', function () {
var value = $(this).val(),
file = value.toLowerCase(),
extension = file.substring(file.lastIndexOf('.') + 1);

if ($.inArray(extension, options.allowedExtensions) == -1) {
options.error();
$(this).focus();
} else {
options.success();

}

});

});
};

})(jQuery);

$(function () {
$('#image').checkFileType({
allowedExtensions: ['jpg', 'jpeg'],
success: function () {
alert('Success');
},
error: function () {
alert('Only JPG image allowed');
}
});

});
</script>
</head>
<body>
<div class="container">
<nav class="navbar navbar-default" role="navigation" style="background-color: #b2a7d0; border-color:#b2a7d0; ">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Image upload and display image using php</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="gallery.php">Home</a></li>
<li><a href="listImages.php">List Images</a></li>
<li class="active"><a href="imageUpload.php">Upload Images</a></li>                        
<li><a href="logout.php">logout</a></li>
</ul>                    
</div><!--/.nav-collapse -->
</div><!--/.container-fluid -->
</nav>
<form style="padding: 50px;"name="frmImage" enctype="multipart/form-data" action="" method="post" class="frmImageUpload form-horizontal"  onsubmit="return validation(thisform)">

<div class="form-group">
<label class="control-label col-lg-4">Title</label>
<div class="col-lg-3">
<input type="text" name="name" class="form-control">
</div>
</div>          
<div class="form-group">
<label class="control-label col-lg-4">Upload Image File:</label>
<div class="col-lg-1">
<input name="userImage" type="file" class="inputFile" id="image"  />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-10">
<input type="submit" value="Submit" class="btnSubmit" name="submit"/>
</div>
</div>
</form>
</div>
</body>
</html>


Step6: imageView Page

display image
image view screen shot

 imageView.php

<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("image") or die(mysql_error());
if(isset($_GET['image_id'])) {
$sql = "SELECT imageType,imageData FROM output_images WHERE imageId=" . $_GET['image_id'];
$result = mysql_query("$sql") or die("<b>Error:</b> Problem on Retrieving Image BLOB<br/>" . mysql_error());
$row = mysql_fetch_array($result);
header("Content-type: " . $row["imageType"]);
echo $row["imageData"];
}
mysql_close($conn);
?>


Step7: admin.php:

<!DOCTYPE>
<html>
<head>
<title>san web tutorials</title> </head>
<link href="css/vendor/bootstrap.min.css" rel="stylesheet" type="text/css">
<style>
body {
padding-top: 50px;
padding-bottom: 50px;
background-color:#FFF;
color:#003399;
}
.login{
margin-top: 200px;
margin-left: 300px;
}
</style>
<body>
<div class="container">
<a class="navbar-brand" href="#">Image upload and display image using php</a>
<fieldset class="login">

<form method="post" action="login.php" class="form-horizontal">
<h3 style="padding-left: 150px; padding-bottom: 20px;">Administration login</h3>
<div class="form-group">
<label class="col-sm-2 control-label">Username </label>
<div class="col-sm-4">
<input name="login" type="text" id="login" value="admin" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"> Password</label>
<div class="col-sm-4">
<input name="password" type="password" id="password" value="password" class="form-control" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" name="button" id="button" value="Login"  class="btn btn-default"/>
</div>
</div>

</form>
</fieldset>
</div>
</body>
</html>

Step8: delete.php:

<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("image");
$imageId = $_REQUEST['imageId'];
$sql = "DELETE FROM output_images WHERE imageId=$imageId";
$result = mysql_query($sql);
header("Location: listImages.php");
?>


Step9: gallery Page


display image from database
display image from database


 gallery.php

<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("image");
$sql = "SELECT imageId FROM output_images ORDER BY imageId asc";
$result = mysql_query($sql);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>gallery page</title>
</head>
<body>
<a class="navbar-brand" href="#">Image upload and display image using php</a>
<?php
while ($row = mysql_fetch_array($result)) {
echo '<div class="pic">';
echo '<a>';
?>
<img width="250" height="250" style="float:left; padding:20px; border:1px solid #039;" class="img" align="middle" src="imageView.php?image_id=<?php echo $row["imageId"]; ?>" />
<?php
echo '</a>';
echo '</div>';
}
mysql_close($conn);
?>
</body>
</html>


Step10: listImages.php


<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("image");
$sql = "SELECT imageId FROM output_images ORDER BY imageId DESC";

$result = mysql_query($sql);

?>
<html>
<head>
<title>display image from database table</title>
<link href="css/vendor/bootstrap.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<nav class="navbar navbar-default" role="navigation" style="background-color: #b2a7d0; border-color:#b2a7d0; ">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">upload image and display it</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="gallery.php">Home</a></li>
<li class="active"><a href="listImages.php">List Images</a></li>
<li><a href="imageUpload.php">Upload Images</a></li>
<li><a href="logout.php">logout</a></li>
</ul>                    
</div>
</div>
</nav>
<h3>Service List</h3>

<?php
while ($row = mysql_fetch_array($result)) {
?>
<div class="row">
<div class="col-xs-3">
<a href="#" class="thumbnail">

<img alt="125x125"  src="imageView.php?image_id=<?php echo $row["imageId"]; ?>" />
</a>
</div>
<div class="col-xs-3">                    
<a href="delete.php?imageId=<?php echo $row['imageId']; ?>"> Delete </a>                        
</div>
</div>

<?php
}
mysql_close($conn);
?>
</div>
</body>
</html>

Step11: login.php

<?php

//Start session
session_start();

//Array to store validation errors
$errmsg_arr = array();

//Validation error flag
$errflag = false;

//Connect to mysql server
$link = mysql_connect("localhost", "root", "");
if (!$link) {
    die('Failed to connect to server: ' . mysql_error());
}

//Select database
$db = mysql_select_db("image");
if (!$db) {
    die("Unable to select database");
}

//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
    $str = @trim($str);
    if (get_magic_quotes_gpc()) {
        $str = stripslashes($str);
    }
    return mysql_real_escape_string($str);
}

//Sanitize the POST values
$login = clean($_POST['login']);
$password = clean($_POST['password']);

//Input Validations
if ($login == '') {
    $errmsg_arr[] = 'Login ID missing';
    $errflag = true;
}
if ($password == '') {
    $errmsg_arr[] = 'Password missing';
    $errflag = true;
}

//If there are input validations, redirect back to the login form
if ($errflag) {
    $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
    session_write_close();
    header("location:index.php?msg=error");
    exit();
}

//Query to check database for record
$qry = "select * from login where username='" . $_POST['login'] . "' and password='" . $_POST['password'] . "'";
$result = mysql_query($qry);

//Check whether the query was successful or not
if ($result) {
    if (mysql_num_rows($result) == 1) {
        //Login Successful
        session_regenerate_id();
        $member = mysql_fetch_assoc($result);

        //Set session
        $_SESSION['SESS_MEMBER_ID'] = $member['id'];
        //Put name in session
        $_SESSION['SESS_FIRST_NAME'] = $member['login'];
        //Close session writing
        session_write_close();

        //Redirect to user's page
        header("location: listImages.php");
        exit();
    } else {
        //If Login failed redirect to login page
        header("location: index.php?msg=error");
        exit();
    }
} else {
    die("Query failed");
}
?>

Step12: logout.php


<?php
//Start session
session_start();
//Unset the variables stored in session
unset($_SESSION['SESS_MEMBER_ID']);
unset($_SESSION['SESS_FIRST_NAME']);
session_destroy();
//redirect to login page
header('Location:gallery.php?msg=logout');
?>

and also add two more files find this files in downloaded link below , 

 <link href="css/vendor/bootstrap.min.css" rel="stylesheet" type="text/css" />
  <script src="js/vendor/jquery-1.8.3.min.js" type="text/javascript" ></script>

 I hope this scripts are really helpful for you. Thanks my next post soon..............