2012-03-18 60 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/”还要检查权限。