javascript - What do we do if we want to insert multiple images uploaded by dragdrop in one line at a time?

i used by javascrip upload multiple file but that files insert different columns.

Why is it that when uploading multiple files with drag drop, they are written in multiple rows instead of one line in the database? Pictured is a view of the data after inserting it into the database My php Code is : uploads.php

if(isset($_FILES)){
    $upload_dir = "upload/";
    $fileName = strtolower(pathinfo($_FILES["files"]["name"], PATHINFO_EXTENSION));
    $new_file_name = rand() . '.' . $fileName;
    $uploaded_file = $upload_dir.$new_file_name;    
    if(move_uploaded_file($_FILES['files']['tmp_name'],$uploaded_file)){
        
      
       } 

        $content = $_POST['textpost'];

        $data = array(
            ':file'          =>  $new_file_name,
            ':uploaded_on'          =>  date("Y-m-d H:i:s"),
            ':content'          => $content,
        );
     $query = "
            INSERT INTO images 
            (name, uploaded_on ,content) 
            VALUES (:name,:uploaded_on,:content)
            ";
       
         $statement = $connect->prepare($query);
         $statement->execute($data);
    }

The Below is the code I originally used. I used these codes as examples from other people??�s codes. Then I made some changes myself and added a little functionality. For example, I added a few codes, such as deleting images, separating images and videos, and brought them to the function I needed. But the problem with me now is that When uploading multiple images at the same time as text, All data sent are insert into separate rows, Finally when I select the data from the database the content and images are not select out correctly.My goal is to insert images and text into a single line. My javascript Code is :index.html

var  dropRegion = document.getElementById("drop-region"),
  // where images are previewed
  imagePreviewRegion = document.getElementById("image-preview");
 var file_drag_area = document.getElementById("file_drag_area");
 var images_button = document.getElementById("images_btn");
  var submit = document.getElementById("submit");
// open file selector when clicked on the drop region 
var fakeInput = document.createElement("input");
fakeInput.type = "file";
fakeInput.accept = "video/*,image/*";
fakeInput.multiple = true;

images_button.addEventListener('click', function() {
  fakeInput.click();
});

fakeInput.addEventListener("change", function() {
  var files = fakeInput.files;
  handleFiles(files);
});


function preventDefault(e) {
  e.preventDefault();
    e.stopPropagation();
}
file_drag_area.addEventListener('dragenter', preventDefault,  false)
file_drag_area.addEventListener('dragleave', preventDefault, false)
file_drag_area.addEventListener('dragover', preventDefault, false)
file_drag_area.addEventListener('drop', preventDefault, false)

dropRegion.addEventListener('dragenter', preventDefault, false)
dropRegion.addEventListener('dragleave', preventDefault, false)
dropRegion.addEventListener('dragover', preventDefault, false)
dropRegion.addEventListener('drop', preventDefault, false)
function handleDrop(e) {
  var dt = e.dataTransfer,
    files = dt.files;
 
  handleFiles(files)
     
}

dropRegion.addEventListener('drop', handleDrop, false);
file_drag_area.addEventListener('drop', handleDrop, false);

// when drag file the border change to other dotted 
file_drag_area.addEventListener("dragenter", function(event) {
  if ( event.target.className == "file_drag_area" ) {
    event.target.style.border = "3px dotted #79d4ff";
  }
});
// when drag file the border display none 
file_drag_area.addEventListener("dragleave", function(event) {
  if ( event.target.className == "trigger_popup_fricc_wrapper" ) {
    event.target.style.border = "";
  }
});

file_drag_area.addEventListener("drop", function(event) {
  if ( event.target.className == "trigger_popup_fricc_wrapper" ) {
    event.target.style.border = "";
  }
});



function handleFiles(files) {
  for (var i = 0, len = files.length; i < len; i++) {
    if (validateImage(files[i]))
      previewAnduploadImage(files[i]);
  }
}
function validateImage(image) {
  // check the type
   var   validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg','video/mp4', 'video/mkv', 'video/webm'];
   var vedioType = validTypes.includes('video/mp4', 'video/mkv', 'video/webm');
  if (validTypes.indexOf( image.type ) === -1 && vedioType.indexOf( video.type ) === -1) {
    alert("Invalid File Type");
    return false;
  }
  
  // check the size
  var maxSizeInBytes = 10e6; // 10MB

  if (image.size > maxSizeInBytes) {
    alert("File too large");
    return false;
  }
  
  return true;
    
}

function previewAnduploadImage(image) {

       var fileType = image.type; 
 

   var match = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg','video/mp4', 'video/mkv', 'video/webm'];
   if ((fileType == match[0]) || (fileType == match[1]) || (fileType == match[2]) || (fileType == match[3])) {

  var imgView = document.createElement("div");
  imgView.className = "image-view";
  imagePreviewRegion.appendChild(imgView);
var icon = document.createElement("div")
icon.className = "image-icon";
//icon.setAttribute("onclick", "remove_image()");
imgView.appendChild(icon);
 
  var remove = document.createElement("img")
  remove.className = "img_class";
  remove.setAttribute("height", "20px");
    remove.setAttribute("width", "20px");
    remove.setAttribute("src", "../../assets/images/cancel.png");
  icon.appendChild(remove);

  // previewing image
  var img = document.createElement("img");
  img.className = "remove_input";
  img.setAttribute("height", "200px");
    img.setAttribute("width", "300px");
  imgView.appendChild(img);
  var reader = new FileReader();
  reader.onload = function(e) {
    img.src = e.target.result;
  }
  reader.readAsDataURL(image);

}else if ((fileType == match[4]) || (fileType == match[5]) || (fileType == match[6])) {

// show video

  var video = document.createElement("video")
    video.classList.add("obj");
    video.file = image;
    video.className = "preview_vedio";
    video.controls = true;
     video.autoplay = true;
     video.setAttribute("width", "500");
  video.setAttribute("height", "300");
//icon.setAttribute("onclick", "remove_image()");
   imagePreviewRegion.appendChild(video);
    var reader = new FileReader();
    reader.onload = function(e) {
    video.src = e.target.result;
  }
  reader.readAsDataURL(image);
     
}
  var formData = new FormData();
  formData.append('image', image);  
  formData.append('action', 'files');
  //formData.append('vedio', vediofiles);
   $("#drop-region").css("display", "block"); 
 $("#drop-region").slideDown("slow")

 addEventListener('submit', (event) => {
var uploadLocation = 'uploads.php';
    var ajax = new XMLHttpRequest();
  ajax.open("POST", uploadLocation, true);

  ajax.onreadystatechange = function(e) {
    if (ajax.readyState === 4) {

      if (ajax.status === 200) {
         //var myObj = JSON.parse(this.responseText);

      } else {
        // error!
      }
    }
  }

  ajax.upload.onprogress = function(e) {

    // change progress
    // (reduce the width of overlay)

    var perc = (e.loaded / e.total * 100) || 100,
      width = 100 - perc;

    overlay.style.width = width;
  }

  ajax.send(formData);
});

}
textarea 
{
   width: 100%;
   margin: 0px;
    padding: .2em;
    border: none;
    outline-width: 0;
    text-align: start;
    unicode-bidi: plaintext;
    font-weight: 400;
    cursor: text;
    background-color: #ffffff;
    overflow:hidden;
    resize: none;
     font-size: 18px; 
} 
input#submit {
   width: 100%;
    color: white;
    background: #79d4ff;
    font-size: 18px;
    border: none;
    border-radius: 8px;
    outline-width: 0;
    line-height: 2;
}
input#submit:hover
{
  background: #3da0f5;
}
input#submit:focus{width: 98%;}
#drop-region {
  background-color: #fff;
  border-radius:20px;
  box-shadow:0 0 35px rgba(0,0,0,0.05);
  padding:60px 40px;
  text-align: center;
  cursor:pointer;
  transition:.3s;
  display:none;
}
#drop-region:hover {
  box-shadow:0 0 45px rgba(0,0,0,0.1);
}

#image-preview {
  margin-top:20px;
  
}
#image-preview .image-view {
    display: inline-block;
  position:relative;
  margin-right: 13px;
  margin-bottom: 13px;
}
#image-preview .image-view img {
    max-width: 300px;
    max-height: 300px;
    transform: scale(.9);
  transition: .4s;
}
#image-preview .overlay {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    right: 0;
    z-index: 2;
    background: rgba(255,255,255,0.5);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<form id="fupForm"enctype="multipart/form-data" accept-charset="utf-8">
  <textarea style="direction:ltr;"  name="post_content" class="file_drag_area" id="file_drag_area" maxlength="1000"   placeholder="Greate Post..." ></textarea>
<div id="drop-region">
<div id="image-preview">
  </div>
</div>
  <button type="button"  class="emoji_button" id="images_btn"><img  src="../../assets/images/image.png" width="25px" height="25px" ></button>
<input type="submit" name="submit" id="submit" class="btn btn-primary" value="Send Post" />
</form>

Answer

Solution:

For your case, when you drag and drop the files (file upload), you will trigger the following function:

function handleFiles(files) {
  for (var i = 0, len = files.length; i < len; i++) {
    if (validateImage(files[i]))
      previewAnduploadImage(files[i]);
  }
}

It is obvious that this "handleFiles" function will process the files one by one. Hence the php is called ONCE for every file uploaded --- and that explains why the files are saved into separate records.

The above should explain what you encounter. So if you want to save the data into a single record, you need to amend the above codes

Source