2013-09-27 83 views
0

我想更新我的上傳文件夾和mysql數據庫中的圖像文件上傳給文件名0.jpg,而不是正常人ID 13.jpg,並沒有更新MySQL數據庫,這是我的代碼片段下面是我做錯了什麼?更新上傳文件夾中的圖像和mysql中的圖像路徑

$pic = mysql_real_escape_string(htmlspecialchars($_FILES['photo']['name'])); 



    //This gets all the other information from the form 

$pic=($_FILES['photo']['name']); 

    $file = $_FILES['photo']['name']; // Get the name of the file (including file extension). 
    $ext = substr($file, strpos($file,'.'), strlen($file)-1); 
    if(!in_array($ext,$allowed_filetypes))//check if file type is allowed 
     die('The file extension you attempted to upload is not allowed.'); //not allowed 
    if(filesize($_FILES['photo']['tmp_name']) > $max_filesize) //check that filesize is less than 50MB 
     die ('The file you attempted to upload is too large, compress it below 50MB.'); 


    // Connects to your Database 
    mysql_connect("localhost", "root", "") or die(mysql_error()) ; 
    mysql_select_db("office") or die(mysql_error()) ; 

    //Writes the information to the 



    $target = "images/" .mysql_insert_id() . $ext; 

    $staff_id = mysql_insert_id(); 
    $new_file_name = mysql_insert_id() . $ext; 


    //I removed ,photo='$target' to display only id as picture name 
    mysql_query("UPDATE development SET photo='$new_file_name' WHERE staff_id=$staff_id"); 


//Writes the file to the server 
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) 
{ 

//Tells you if its all ok 
    echo "The file ". basename($_FILES['photo']['name']). " has been uploaded, and your information has been added to the directory"; 
} 
else { 

//Gives and error if its not 
echo "Sorry, there was a problem uploading your file."; 
} 
?> 
+4

你打電話'mysql_insert_id()'沒有做過插入,所以你找回布爾值false/0值。 –

回答

0

取而代之的是

$staff_id = mysql_insert_id(); $new_file_name = mysql_insert_id() . $ext;

//I removed ,photo='$target' to display only id as picture name mysql_query("UPDATE development SET photo='$new_file_name' WHERE staff_id=$staff_id");

做類似這樣

mysql_query ("INSERT INTO development (photo) VALUES ('".$new_file_name."')");  
//first insert 
$staff_id = mysql_insert_id() ;  
// then get the id of the record you've just inserted 
+0

小心。開發可能不是用戶/人員表。如果不是,你將獲得開發的主鍵而不是用戶。 –

+0

並且可能整個架構都是錯誤的。 –

+0

並且可能整個架構都是錯誤的。我想你需要一張上傳的文件和一張人員(工作人員)的表格。每個用戶可以上傳許多圖像。 因此,您首先需要將新圖片與上傳圖片的用戶的ID(獲取此用戶的標識,您可能需要另一個查詢或您在會話中擁有的圖片)一起插入圖片表中。然後,您可以獲得剛剛上傳的圖像的標識,並執行您需要的任何操作,例如,將其存儲在用戶的表格中,如果您有像「上次提交的圖像」字段那樣的內容。 –

0

首先,您使用的是mysql_ *本功能離子,從5.5開始不推薦使用。

其次,您需要查看mysql_insert_id的手冊頁。報價:

檢索由以前的查詢(通常是INSERT) 爲AUTO_INCREMENT列生成的ID。

這意味着您只能在調用mysql_insert_id()後插入數據或更新用戶/人表。然而,在你的情況下,好像你已經有了存儲在變量$staff_id中的人的ID,所以你可能甚至不需要使用mysql_insert_id。這不會起作用嗎?

$target = "images/" . $staff_id . $ext; 
+0

我試過你的解決方案,但它給了我注意:未定義變量:staff_id – user2821383

相關問題