2012-03-18 94 views
0

我想上傳文件到服務器上使用PHP,但我需要一些幫助。文件上傳php mysql

我有一個HTML表單提交書名和書籍圖像。書名將被存儲在數據庫中(見下文),圖像將被存儲在服務器上。

標識,書名和日期正在存儲在數據庫中,但是圖像未上傳。請幫我整理一下。

謝謝。

數據庫表「書」

id int(11), book_name varchar(255), date_added date 

add_book.php

<?php 

$book_name = $_POST['book']; 

// insert fields to database 
$sql_query = mysql_query("INSERT INTO books (book_name, date_added) VALUES ('$book_name', now()"); 


// get id for that row 
$id = mysql_insert_id(); 

// rename the book to that id followed by the format .jpg 

$new_book_name = "$id.jpg"; 

// define upload path 
$upload_path = "../book_images/"; 

// move the uploaded file to the upload path with the new name 
move_uploaded_file($_FILES['upload']['tmp_name'], $upload_path . $new_book_name); 

?> 

<form action="add_book.php" method="post" enctype="multipart/form-data" name="bookform"  id="bookform"> 

Book name: <input name="book" type="text" id="book" value=""/> <br /> 
Book image: <input type="file" name="upload" id="upload" /> 

<input name="submit" type="submit" value="Add book" /> 
</form> 
+0

羅斯的東西可能會出現上傳錯誤。不要盲目嘗試複製文件,請首先檢查$ _FILES ['upload'] ['error']。 – Corbin 2012-03-18 21:33:48

回答

0

之前任何PHP開發人員開始調試任何東西,我總是在每一個都設置error_reporting(E_ALL);ini_set("display_errors", 1);在最高層的問題建議你的腳本。這會告訴你在什麼語句/變量/常量的哪一行出了問題

無論如何,你應該檢查文件上傳與否,它的類型和其他這樣的參數的有效性。你也應該把它存儲通過增加相對路徑相對於當前的工作目錄

if(isset($_FILES["upload"])&&$_SERVER["REQUEST_METHOD"]=="POST") 
{ 
    $name=$_FILES["upload"]["name"]; 

    $tempName=$_FILES["upload"]["tmp_name"]; 

    $size=$_FILES["upload"]["size"]; 

    $type=$_FILES["upload"]["type"]; 

    $realPath="bookName/Imagename/".$name; 

    if(($type=="image/jpg"||$type=="image/jpeg"||$type=="image/png")) 
    { 
     if(is_dir($fullDirectory)) //if directory exists, then simply move it 
     { 
     move_uploaded_file($tempName, $realPath); 
     } 
     else //if directory doesn't exist then make one and then move the file 
     { 
     mkdir($fullDirectory,0777,true); 

     move_uploaded_file($tempName, $realPath); 

     } 
    } 
    else 
    { 
    print $_FILES["upload"]["error"]; 
    } 
    } 
0

SPME的事情是錯在這裏:

$new_book_name = "$id.jpg"; 

你應該把文件名從POST這裏$_FILES["upload"]["name"]。並添加$ ID,文件名爲:

$new_book_name = $id."-".$_FILES["upload"]["name"]; 

在你的上傳目錄「../book_images/」還要檢查權限。