문제

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>
도움이 되었습니까?

해결책

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
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top