2016-05-16 42 views
-2

我對PHP和mySql非常陌生,但正在努力學習一個項目。我遵循本教程http://www.formget.com/ajax-image-upload-php/,以便能夠將圖像作爲列上載到MySQL數據庫中具有諸如圖像大小,ID等行的圖像列中。將圖像插入MySQL表中列中的行而不是單個列?

我有一個單獨的數據表,我爲每個用戶創建列帳戶(每個帳戶都有一行用戶名,密碼等)。我在這些列中創建了一行來存儲Blob。

我不需要教程爲其圖像創建的所有行(image_type,size等),但實際上只需要圖像源(圖像行)。我需要將此圖像插入到我的帳戶列中的圖像的ROW(取決於登錄的帳戶),而不是爲每個圖像創建新列。我不知道如何用我的代碼去解決這個問題。在這裏我爲我的HTML表單的JavaScript:

$(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'); 
     }; 
}); 

然後引用upload.php的,這也正是需要做出改變:

<?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>"; 
} 
} 

?> 

我試圖想切出圖像尺寸參考,類型等,因爲我覺得這些都是不必要的,但是這會產生錯誤。我倒了其他SO帖子,但不知道如何簡單地插入一個圖像到MySQL數據庫中的EXISTING列中的行。我只能創建圖像的新列。

我該如何做到這一點?

+0

'mysql'和'sql-server'不是一回事。你正在使用'mysql'('new PDO(「mysql:..')。僅僅因爲你命名了你的數據庫'sqlserver'並不會使它成爲'sql-server'。 – Sean

+1

如果你想將圖像添加到現有的你需要將你的'INSERT INTO ...'查詢改成'UPDATE ...'查詢,在'UPDATE'查詢中你需要使用'WHERE columnName = value'。'columnName = value'是你可以指定你的登錄用戶 – Sean

+1

上面的教程清楚地告訴你如何將圖像作爲blob插入到表格中,現在你必須將它插入到不同的表格中,你只需要應用你所擁有的從教程中學習如果你不明白它在做什麼,那麼返回到教程並重新閱讀它,或者詢問一個關於你不明白的具體問題,但是請不要讓我們重寫教程的內容代碼來滿足您的需求。 – Shadow

回答

0

出於各種原因,通常將文件存儲在數據庫中通常是not。雖然該規則有一些例外情況,但您應確定這是最適合您的解決方案。

相反,首先要問爲什麼要這樣做,爲什麼將文件存儲在磁盤上,然後在數據庫中跟蹤文件名不是首選解決方案。一旦你可以證明你的用例,(如果你可以證明你的用例),那麼你應該問如何實現它。

相關問題