2012-03-20 162 views
0

我是新來的PHP和試圖上傳圖像文件在MySQL數據庫使用php.I試過各種教程,但它沒有爲我工作。 代碼段: -上傳圖像到MySQL使用php

<?php 
//connect to database. Username and password need to be changed 
mysql_connect("localhost", "root", ""); 

//Select database, database_name needs to be changed 
mysql_select_db("yelldb"); 

if (!$_POST['uploaded']){ 
//If nothing has been uploaded display the form 
?> 

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" 
ENCTYPE="multipart/form-data"> 
Upload:<br><br> 
<input type="file" name="image"><br><br> 
<input type="hidden" name="uploaded" value="1"> 
<input type="submit" value="Upload"> 
</form> 

<?php 
}else{ 
//if the form hasn't been submitted then: 

//from here onwards, we are copying the file to the directory you made earlier, so it can then be moved 
//into the database. The image is named after the persons IP address until it gets moved into the database 

//get users IP 
$ip=$_SERVER['REMOTE_ADDR']; 


//don't continue if an image hasn't been uploaded 
if (!empty($image)){ 
//copy the image to directory 

copy($image, "./temporary/".$ip.""); 

//open the copied image, ready to encode into text to go into the database 
$filename1 = "./temporary/".$_SERVER['REMOTE_ADDR']; 
$fp1 = fopen($filename1, "r"); 

//record the image contents into a variable 
$contents1 = fread($fp1, filesize($filename1)); 

//close the file 
fclose($fp1); 

//encode the image into text 
$encoded = chunk_split(base64_encode($contents1)); 

//insert information into the database 
mysql_query("INSERT INTO servicelist (ImgData)"."VALUES ('$encoded')"); 

//delete the temporary file we made 
//unlink($filename1); 
} 
} 
?> 
+0

你會得到什麼錯誤? – 2012-03-20 12:56:36

+0

我沒有收到任何錯誤。只是一個空白的屏幕。 – 2012-03-20 13:06:17

+0

什麼文章或書你正在學習文件上傳? – 2012-03-20 14:02:11

回答

0

我們不會在我們的數據庫中保存了整個圖像一般。我們經過將圖片的永久插入我們的數據庫中。使用此php功能

move_uploaded_file(file,newloc) 

這將從您的臨時目錄移到永久目錄。然後,從那裏獲取路徑並將其插入數據庫。

0

通常,您不會將整個圖像保存到SQL數據庫中。相反,您將磁盤路徑或其他「指針」存儲在實際文件中。

更改您的代碼來讀取類似如下:

//don't continue if an image hasn't been uploaded 
if (isset($_POST['image'])){ 
$image = $_POST['image']; 
//copy the image to directory 
$path = "/some/path"; 

move_uploaded_file($image,$path); 

//store the name and path. PS: you will want to validate your input, and look 
//at using prepared statements. 
//Concentating values like this is NOT safe, or ideal 

$location = $path . "/" . $image 
mysql_query("INSERT INTO servicelist (ImgData) VALUES (" . $location . ")"); 
} 

但是,如果您仍然希望將圖像存儲在SQL數據庫,尋找到Blob存儲類型,而不是編碼的文本。

PHP move_uploaded_file

+0

@penguineCoder: - 感謝您的回覆,但這不起作用。 我試着調試它,發現如果(!empty($ image))這個條件沒有進入內部控制。任何想法? – 2012-03-20 13:11:04

+0

@AbhinandanSahgal更新我的代碼。看看它的一般流程,並嘗試適應你的使用。 – PenguinCoder 2012-03-20 13:21:09

+0

如果條件還是沒有進去。 – 2012-03-20 13:36:29