2011-07-15 71 views
0

我想刪除一個id數組,當它被刪除時,我想上傳的圖片與它關聯也使用unlink刪除。我在Joomla的admin mvc組件中使用joomla和mysql。從joomla中刪除上傳的文件時,它們是否被刪除?

我對控制器刪除代碼具有如下:

function remove() 
{ 
     $arrayIDs = JRequest::getVar ('cid', null, 'default', 'array'); 
//Reads cid as an array 
     $model = & $this->getModel ('greetings'); 
     jimport ('joomla.filesystem.file'); 
     if (is_array ($arrayIDs) && count ($arrayIDs) > 0) { 

      foreach ($arrayIDs as $k => $id) { 

       $del = $model->deleteGreetings ($arrayIDs); 



       if ($del) { 

        $getdeleted = $model->getUploadpic ($id); 

        $deletefile = JPATH_COMPONENT . DS . "uploads" . DS . $uploadedfile; 

        unlink ($deletefile); 

       } 

      } 
     } 

     if ($arrayIDs === null) { //Make sure the cid parameter was in the request 
      JError::raiseError (500, 'cid parameter missing from the request'); 
     } 

     $redirectTo = JRoute::_ ('index.php?option=' . JRequest::getVar ('option')); 
     $this->setRedirect ($redirectTo, 'Deleted...'); 

    } 

...和模型我的代碼是:

function deleteGreetings($arrayIDs) { 
     $query = "DELETE FROM #__greetings WHERE id IN (" . implode (',', $arrayIDs) . ")"; 
     $db = $this->getDBO(); 
     $db->setQuery ($query); 
     if (! $db->query()) { 
      $errorMessage = $this->getDBO()->getErrorMsg(); 
      JError::raiseError (500, 'Error deleting greetings: ' . $errorMessage); 
     } else { 
      return TRUE; 
     } 
    } 

回答

1

你在你的代碼的一些問題:

  1. $uploadedfile從未聲明,但它用於查找文件路徑。我認爲這與$getdeleted相同。
  2. 你有一個foreach循環環繞數組中的元素,它將依次拾取每個元素。但是你的模型功能deleteGreetings佔用整個陣列。你應該從你的循環中刪除這個函數調用,否則它將被調用每個元素在數組中。你只想調用一次。
  3. 只有在你的控制器的末尾,你檢查你的cid參數是否爲空......有什麼意義?在嘗試運行任何其他代碼之前,應先檢查它。

我會做這樣的事情:

$arrayIDs = JRequest::getVar ('cid', null, 'default', 'array'); 
if ($arrayIDs === null) { //Make sure the cid parameter was in the request 
    JError::raiseError (500, 'cid parameter missing from the request'); 
} 
$model = & $this->getModel ('greetings'); 
jimport ('joomla.filesystem.file'); 
if (is_array ($arrayIDs) && count ($arrayIDs) > 0) { 
    $del = $model->deleteGreetings ($arrayIDs); 
    // check this outside the loop, if it is inside you are checking it for 
    // each element in the array. Here we check once and then go forward. 
    if ($del) { 
    foreach ($arrayIDs as $k => $id) { 
     $uploadedfile = $model->getUploadpic ($id); 
     $deletefile = JPATH_COMPONENT . DS . "uploads" . DS . $uploadedfile; 
     JFile::delete($deletefile); 
     //unlink ($deletefile); 
    } 
    } 
} 
+0

這是一個較舊的答案,我想補充一點,你不應該使用JRequest或JError更多,因爲他們已經被棄用。 – Elin

相關問題