Domanda

I have a select box where users can choose files they want to be attached to their system. Each of the files that get selected are inserted into the database. However, if they unselect that file, I want it's row removed from the database.

Without removing all the files attached to that user on that system and reinserting the now-selected files, how would I remove the previously-selected files that are no longer needed?

<select name="choose_files[]" class="multi-select" multiple="" id="attach_files">
<?php
  foreach ($files AS $file) { 
    echo '<option value="' . $file['id'] . '"';
    if ($file['id'] === $compared['file_id']) 
    { echo ' SELECTED';}
  }
   echo '>' . $file['originalFilename'] . '</option>';
  } ?>
 </select>
È stato utile?

Soluzione

You can use array_diff(). For example:

$current_files = get_current_files();
$post_files = $_POST['choose_files'];

$remove = array_diff($current_files, $post_files);
$add = array_diff($post_files, $current_files);

if (!empty($remove)) {
    // remove these files from DB
}

if (!empty($add)) {
    // add these files to DB
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top