Welcome Guest, Not a member yet? Register   Sign In
Delete multiple rows from database table
#1

PHP Code:
  function delete()
  {
    foreach ($this->request->getPost('checkbox') as $id)
    {
      $path_thumb '../media/images/uploads/'.$id.'/thumb';
      if (is_dir($path_thumb))
      {
        delete_files($path_thumb); 
        rmdir($path_thumb);
      }

      $path '../media/images/uploads/'.$id;
      if (is_dir($path))
      {
        delete_files($path); 
        rmdir($path);
      }

      $articlesModel = new ArticlesModel();
      $imagesModel = new ImagesModel();

      $deleteImages $imagesModel->where('id_article'$id)->delete();
      $deleteArticles $articlesModel->where('id'$id)->delete();

      if($deleteImages && $deleteArticles)
      {
        return redirect()->to(base_url('articles'))->with('success''Gli articoli selezionati sono stati eliminati!');
      }
      else
      {
        return redirect()->to(base_url('articles'))->with('danger''Errore! Impossibile eliminare i dati nel database.');
      }
    

I would like delete multiple rows from my table. I have an array of checkbox. How can i do? Thanks.
Reply
#2

You can use whereIn() to target multiple IDs.
Reply
#3

If i use this snippet:
PHP Code:
$deleteImages $imagesModel->whereIn('id_article'$id)->delete();
$deleteArticles $articlesModel->whereIn('id'$id)->delete(); 

I have an error:
Code:
CodeIgniter\Database\Exceptions\DatabaseException #8
Deletes are not allowed unless they contain a "where" or "like" clause.

Please, can you write the correct query for delete multiple rows? Thanks for help me.
Reply
#4

I think you are required to put in an array. Right now you are just entering one id.

This need to be run outside your foreach, as you need to populate $ids array with all $id elements.
PHP Code:
$ids = [12345]; // Id's to delete.
$deleteImages $imagesModel->whereIn('id_article'$ids)->delete();
$deleteArticles $articlesModel->whereIn('id'$ids)->delete(); 
Reply
#5

(This post was last modified: 05-06-2020, 07:47 AM by eleumas.)

(05-05-2020, 11:35 AM)jreklund Wrote: I think you are required to put in an array. Right now you are just entering one id.

This need to be run outside your foreach, as you need to populate $ids array with all $id elements.
PHP Code:
$ids = [12345]; // Id's to delete.
$deleteImages $imagesModel->whereIn('id_article'$ids)->delete();
$deleteArticles $articlesModel->whereIn('id'$ids)->delete(); 

This is the solution for delete multiple rows:

PHP Code:
$id $this->request->getPost('checkbox');
        
$ids = [];

        for($count 0$count count($id); $count++)
        {
          $ids[] = $id[$count];
        }

        $articlesModel = new ArticlesModel();
        $imagesModel = new ImagesModel();
        $deleteImages $imagesModel->whereIn('id_article'$ids)->delete();
        $deleteArticles $articlesModel->whereIn('id'$ids)->delete(); 
Reply




Theme © iAndrew 2016 - Forum software by © MyBB