私はPHPとmySqlを信じられないほど新しいですが、プロジェクトのために勉強しようとしています。私はこのチュートリアルhttp://www.formget.com/ajax-image-upload-php/に従って、画像サイズ、IDなどの行を持つMySQLデータベースのブロブテーブルの列として画像をアップロードできるようにしました。個々の列ではなく、MySQLテーブルの列内の行にイメージを挿入しますか?
私は個々のユーザーの列を作成する別のデータテーブルを持っていますアカウント(各アカウントにはユーザー名、パスワードなどの行があります)。私はBLOBを格納するためにこれらの列に行を作成しました。
チュートリアルで作成したイメージ(image_type、sizeなど)のすべての行は必要ありませんが、イメージソース(イメージ行)のみが必要です。私はこの画像を自分のアカウントの列の画像(ログインしているアカウントによって異なる)に挿入する必要があります。画像ごとに新しい列を作成する必要はありません。私が持っているコードでこれについてどうやって行くのか分かりません。私の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データベースの既存の列内の行に画像を挿入する方法を理解できません。私は画像の新しい列を作成することしかできません。
どうすればこの問題を解決できますか?
'mysql'と' sql-server'は同じものではありません。 'mysql'(' new PDO( "mysql:..')を使用しています)データベースの名前を 'sqlserver'にすると' sql-server'になりません。 – Sean
イメージを既存の'INSERT INTO ...'クエリを 'UPDATE ...'クエリに変更する必要があります。その 'UPDATE'クエリでは、' WHERE columnName = value'を使う必要があります。 'columnName = value'は – Sean
上記のチュートリアルでは、イメージをBLOBとしてテーブルに挿入する方法を明確に示していますが、別のテーブルに挿入する必要があります。チュートリアルで学んだことを理解していない場合は、チュートリアルに戻ってもう一度やり直してください。また、理解していないことに関する特定の質問をしてください。あなたのニーズに合わせたコード – Shadow