skyguy skyguy - 6 months ago 5
SQL Question

upload image from submit form to mysql database and display image in div?

I am very new to PHP and need to figure this out for a project - I've made an image submit form in HTML that changes the img within a div to the image that selected using the form. Here is how I accomplish this:

echo '<div class="img-container">';
echo '<img class="userimg" src="../images/backgroundplanet.png" />';
echo '<img class="testimg" src="" />'; //stores image from php file
echo '</div>';
echo '<div class="upload-button">Edit Profile</div>';
echo '<input class="file-upload" enctype="multipart/form-data" type="file" name="submit" accept="image/*"/>';
echo '</div>';


and

$(document).ready(function() {


var readURL = function(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();

reader.onload = function (e) {
$('.userimg').attr('src', e.target.result);
}

reader.readAsDataURL(input.files[0]);
}
}


$(".file-upload").on('change', function(){
readURL(this);
});

$(".upload-button").on('click', function() {
$(".file-upload").click();
});
});


I need to upload this image to a column I have created for medium BLOBs in a MySql data base for each individual user. I've tried a number of different methods (tried
$sql = new mysql
, etc) but have no idea what I'm doing.

I'm now following this tutorial - http://www.sevenkb.com/php/how-to-insert-upload-image-into-mysql-database-using-php-and-how-to-display-an-image-in-php-from-mysql-database/ and have written the following that is supposed to upload an image to the database:

if(!isset($_FILES['upload_image']))
{
echo '<p>Please Select Image to Upload</p>';
}
else
{
try {
upload();

echo '<p>Image Uploaded into MySQL Database as LONGBLOB Using PHP </p>';
}
catch(Exception $e)
{
echo '<h4>'.$e->getMessage().'</h4>';
}
}

function upload(){
/*** check if a file was uploaded ***/
echo '<p>you uploaded</p>';

if(is_uploaded_file($_FILES['upload_image']['tmp_name']) && getimagesize($_FILES['upload_image']['tmp_name']) != false)
{
/*** get the image info. ***/
$size = getimagesize($_FILES['upload_image']['tmp_name']);
/*** assign our variables ***/
$type = $size['mime'];
$imgfp = fopen($_FILES['upload_image']['tmp_name'], 'rb');
$size = $size[3];
$name = $_FILES['upload_image']['name'];
$maxsize = 99999999;


/*** check the file is less than the maximum file size ***/
if($_FILES['upload_image']['size'] < $maxsize )
{
/*** connect to db ***/
$dbh = new PDO("mysql:host=localhost;dbname=sqlserver", 'username', 'password');

/*** set the error mode ***/
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

/*** our sql query ***/
$stmt = $dbh->prepare("INSERT INTO img (image_type ,image, image_size, image_name) VALUES (? ,?, ?, ?)");

/*** bind the params ***/
$stmt->bindParam(1, $type);
$stmt->bindParam(2, $imgfp, PDO::PARAM_LOB);
$stmt->bindParam(3, $size);
$stmt->bindParam(4, $name);

/*** execute the query ***/
$stmt->execute();
}
else
{
/*** throw an exception is image is not of type ***/
throw new Exception("File Size Error");
}
}
else
{
// if the file is not less than the maximum allowed, print an error
throw new Exception("Unsupported Image Format!");
}
}


But the image isn't uploading and does not appear in the new column I made in the database. The only thing displayed on the page is "Please Select Image to Upload"

What's wrong here? Ultimately I need to echo this in a div.. What should I do with this?

When trying to run example:

enter image description here

Errors when entering in my table name:

enter image description here

When going to phpadmin: enter image description here

Answer

I have used the code from this link "http://www.formget.com/ajax-image-upload-php/" to get what you needed. This code apart from saving the file into a folder will save it into a database. I have made a folder images to store image files and two php files one which shows frontend html form with javascript code and the other for upload and display. The HTML code "index.php" is this

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<div class="main">
<h1>Ajax Image Upload</h1><br/>
<hr>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div id="image_preview"><img id="previewing" src="noimage.png" /></div>
<hr id="line">
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="file" id="file" required />
<input type="submit" value="Upload" class="submit" />
<input type="hidden" name="image_id" id="image_id" value="2" class="submit" />
</div>
</form>
</div>
<h4 id='loading' >loading..</h4>
<div id="message"></div>

<style>
.userimg {
	width: 50px;
	height:auto;
	
}
</style>

<script type="text/javascript">

  $(document).ready(function (e) {
		$("#uploadimage").on('submit',(function(e) {
		e.preventDefault();
	    $("#message").empty();
		$('#loading').show();
		$.ajax({
		url: "upload.php", // Url to which the request is send
		type: "POST",             // Type of request to be send, called as method
		data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
		contentType: false,       // The content type used when sending data to the server.
		cache: false,             // To unable request pages to be cached
		processData:false,        // To send DOMDocument or non processed data file it is set to false
		success: function(data)   // A function to be called if request succeeds
		{
		$('#loading').hide();
		$("#message").html(data);
		}
		});
		}));
		
		// Function to preview image after validation
		$(function() {
		$("#file").change(function() {
		$("#message").empty(); // To remove the previous error message
		var file = this.files[0];
		var imagefile = file.type;
		var match= ["image/jpeg","image/png","image/jpg"];
		if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
		{
		$('#previewing').attr('src','noimage.png');
		$("#message").html("<p id='error'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>");
		return false;
		}
		else
		{
		var reader = new FileReader();
		reader.onload = imageIsLoaded;
		reader.readAsDataURL(this.files[0]);
		}
		});
		});
		function imageIsLoaded(e) {
		$("#file").css("color","green");
		$('#image_preview').css("display", "block");
		$('#previewing').attr('src', e.target.result);
		$('#previewing').attr('width', '250px');
		$('#previewing').attr('height', '230px');
		};
});

</script>
<style>
body {
font-family: 'Roboto Condensed', sans-serif;
}
h1
{
text-align: center;
background-color: #FEFFED;
height: 70px;
color: rgb(95, 89, 89);
margin: 0 0 -29px 0;
padding-top: 14px;
border-radius: 10px 10px 0 0;
font-size: 35px;
}
.main {
position: absolute;
top: 50px;
left: 20%;
width: 450px;
height:530px;
border: 2px solid gray;
border-radius: 10px;
}
.main label{
color: rgba(0, 0, 0, 0.71);
margin-left: 60px;
}
#image_preview{
position: absolute;
font-size: 30px;
top: 100px;
left: 100px;
width: 250px;
height: 230px;
text-align: center;
line-height: 180px;
font-weight: bold;
color: #C0C0C0;
background-color: #FFFFFF;
overflow: auto;
}
#selectImage{
padding: 19px 21px 14px 15px;
position: absolute;
bottom: 0px;
width: 414px;
background-color: #FEFFED;
border-radius: 10px;
}
.submit{
font-size: 16px;
background: linear-gradient(#ffbc00 5%, #ffdd7f 100%);
border: 1px solid #e5a900;
color: #4E4D4B;
font-weight: bold;
cursor: pointer;
width: 300px;
border-radius: 5px;
padding: 10px 0;
outline: none;
margin-top: 20px;
margin-left: 15%;
}
.submit:hover{
background: linear-gradient(#ffdd7f 5%, #ffbc00 100%);
}
#file {
color: red;
padding: 5px;
border: 5px solid #8BF1B0;
background-color: #8BF1B0;
margin-top: 10px;
border-radius: 5px;
box-shadow: 0 0 15px #626F7E;
margin-left: 15%;
width: 72%;
}
#message{
position:absolute;
top:120px;
left:815px;
}
#success
{
color:green;
}
#invalid
{
color:red;
}
#line
{
margin-top: 274px;
}
#error
{
color:red;
}
#error_message
{
color:blue;
}
#loading
{
display:none;
position:absolute;
top:50px;
left:850px;
font-size:25px;
}
</style>

For the upload script and display after upload (upload.php) you can use

<?php

if(isset($_FILES["file"]["type"]))
{
$validextensions = array("jpeg", "jpg", "png");
$maxsize = 99999999;
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < $maxsize)//Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
}
else
{
if (file_exists("images/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "images/".$_FILES['file']['name']; // Target path where file is to be stored

 $size = getimagesize($_FILES['file']['tmp_name']);
 /*** assign our variables ***/
 $type = $size['mime'];
 $imgfp = fopen($_FILES['file']['tmp_name'], 'rb');
 $size = $size[3];
 $name = $_FILES['file']['name'];



 /*** check the file is less than the maximum file size ***/
 if($_FILES['file']['size'] < $maxsize )
 {
 /*** connect to db ***/
 $dbh = new PDO("mysql:host=localhost;dbname=DM_NAME", 'DB_USER', 'DB_PASSWORD');

 /*** set the error mode ***/
 $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

 /*** our sql query ***/
 $stmt = $dbh->prepare("INSERT INTO imageblob (image_type ,image, image_size, image_name) VALUES (? ,?, ?, ?)");

 /*** bind the params ***/
 $stmt->bindParam(1, $type);
 $stmt->bindParam(2, $imgfp, PDO::PARAM_LOB);
 $stmt->bindParam(3, $size);
 $stmt->bindParam(4, $name);

 /*** execute the query ***/
 $stmt->execute();
 $lastid = $dbh->lastInsertId(); 
 //Move uploaded File
 move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
 if(isset($lastid))
 {
 /*** assign the image id ***/
 $image_id = $lastid;
	 try {
	 /*** connect to the database ***/
	 /*** set the PDO error mode to exception ***/
	 $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	
	 /*** The sql statement ***/
	 $sql = "SELECT image, image_type FROM imageblob WHERE image_id=$image_id";
	
	 /*** prepare the sql ***/
	 $stmt = $dbh->prepare($sql);
	
	 /*** exceute the query ***/
	 $stmt->execute(); 
	
	 /*** set the fetch mode to associative array ***/
	 $stmt->setFetchMode(PDO::FETCH_ASSOC);
	
	 /*** set the header for the image ***/
	 $array = $stmt->fetch();
	 /*** check we have a single image and type ***/
	 if(sizeof($array) == 2)
	 {
		 //To Display Image File from Database
		 echo '<img src="data:image/jpeg;base64,'.base64_encode( $array['image'] ).'"/>';

	 }
	 else
	 {
	 throw new Exception("Out of bounds Error");
	 }
	 }
	 catch(PDOException $e)
	 {
	 echo $e->getMessage();
	 }
	 catch(Exception $e)
	 {
	 echo $e->getMessage();
	 }
	 }
	 else
	 {
	 echo 'Please input correct Image ID';
	 }
 }
 else
 {
 /*** throw an exception is image is not of type ***/
 throw new Exception("File Size Error");
 }
}
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
}
?>

You can download the entire code from here http://www.filehosting.org/file/details/569640/upload.zip. Change the database details and also image displayed is the last insert id in the form . I hope you can do the rest.