I am incredibly new to PHP and mySql but am trying to learn for a project. I have followed this tutorial http://www.formget.com/ajax-image-upload-php/ to be able to upload images as columns in a blob table in a MySQL database with rows such as image size, id, etc.
I have a separate data table where I create columns for individual user accounts (each account has a row for username, password, etc). I have created a row in these columns to store a blob.
I do not need all the rows that the tutorial created for their images (image_type, size, etc) but really just need the image source (the image row). I need to insert this image into the ROW for images in my accounts column (depending on which account is signed in), NOT have new columns be created for each image. I do not know how to go about this with the code I have. Here my JavaScript for my HTML forms:
$(document).ready(function (e) {
//To transfer clicks to divs
$(".upload-button").on('click', function() {
$("#file").click();
});
$(".save").on('click', function() {
$(".submit").click();
});
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$.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
{
}
});
}));
// Function to preview image after validation
$(function() {
$("#file").change(function() {
// 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])))
{
$('.userimg').attr('src','noimage.png');
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");
$('.userimg').attr('src', e.target.result);
$('.userimg').attr('width', '250px');
$('.userimg').attr('height', '230px');
};
});
Which then references upload.php, which is where changes need to be made:
<?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=sqlserver", 'username', '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>";
}
}
?>
I have tried trying to cut out references to image size, type, etc as I feel these are unnecessary, however this created errors. I have poured over other SO posts but can't understand how to simply insert an image into a row within an EXISTING column in mysql data base. I can only create new columns for images.
How can I accomplish this?