2017-04-12 47 views
0

我有問題讓PHP插入圖像路徑或目錄到MySQL數據庫。它只是存儲圖像名稱,而不是圖像的路徑和名稱。此外,我正在重命名圖像以匹配存儲在其下的項目標題(例如藍色車標題,藍色車圖像名稱)。而不是上傳新的圖像名稱,它只存儲原始圖像名稱。插入圖像目錄到MySQL

這是我的重命名並上傳圖像等:

// The directory that will recieve the uploaded file 
$dir = 'uploads/'; 

//variables for images 
$allowedExts = array("gif", "jpeg", "jpg", "png"); 
$temp = explode(".", $_FILES["picture"]["name"]); 
$extension = end($temp);   

if(isset($_POST['submit'])) { 
    if (strlen($title)>0 && strlen($description)>0) { 
      move_uploaded_file($_FILES['picture']['tmp_name'], $dir . "/" . $title ."." . $extension); 


      // Query database and insert data into item table 
      $itemQry = 'INSERT INTO items (title, picture, startPrice, category, description, quantity, location, sellingFormat, duration, paymentType, postageDetails) 
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; 
      $statement = $conn->prepare($itemQry); 
      $statement->bind_param('sssssssssss', $title, $_FILES['picture']['name'], $startPrice, $category, $description, $quantity, $location, $sellingFormat, $duration, $paymentType, $postageDetails); 
      $statement->execute(); 
+0

*它只存儲圖像名稱*因爲這是你告訴它做的 –

+0

$ _FILES ['picture'] ['name']將只返回圖像的名稱(例如file.jpg) – Akintunde007

+0

如何我要改變這個嗎? – Joel

回答

1

試試這個代碼:

// The directory that will recieve the uploaded file 
$dir = 'uploads/'; 

//variables for images 
$allowedExts = array("gif", "jpeg", "jpg", "png"); 
$temp = explode(".", $_FILES["picture"]["name"]); 
$extension = end($temp);   

if(isset($_POST['submit'])) { 
    if ((strlen($title) > 0) && (strlen($description) > 0)) { 
     $newFilePath = $dir . "/" . $title . "." . $extension; 
     move_uploaded_file($_FILES['picture']['tmp_name'], $newFilePath); 

     // Query database and insert data into item table 
     $itemQry = 'INSERT INTO items 
      (title, picture, startPrice, category, description, 
      quantity, location, sellingFormat, duration, 
      paymentType, postageDetails) 
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; 

     $statement = $conn->prepare($itemQry); 
     $statement->bind_param('sssssssssss', $title, $newFilePath, 
         $startPrice, $category, $description, 
         $quantity, $location, $sellingFormat, 
         $duration, $paymentType, $postageDetails); 

     $statement->execute(); 
    } 
} 

注:在這裏,我已經使用$newFilePath作爲一個新的變量,保持路徑和新的文件名並使用相同的名稱插入到數據庫中。希望這可以幫助你:)。

+0

非常好,非常感謝你! – Joel

+0

很高興它幫助! :)但是,從@Akin開始,「請不要僅僅使用擴展名來檢查,而應該使用MIME類型代替,你擁有的東西很容易被欺騙」。照顧這些事情。 – prava