Home > Enterprise >  insert files into mysql and directory but only last inserted file is recorded
insert files into mysql and directory but only last inserted file is recorded

Time:04-09

I have input that stores multiple files in database and directory.

<input id="attachment_file" name="attachment_file" type="file" value="<?=$_POST["attachment_file"]?>"  multiple />

if there are 2 files uploaded i simply want to record them in db and move them to other directory, but the weird thing is that the record is only of the last file that is inserted ... Here is some code:

for ($i=0; $i < count($_FILES['attachment_file']); $i  ) { 
        
        $file_name = $_FILES["attachment_file"]["name"][$i];
        $tmp_name = $_FILES['attachment_file']['tmp_name'][$i];
        $docs_dir = F_FS_PATH_USER_PHOTOS."files/docs/";

        if(!is_dir($docs_dir)) {
            mkdir($docs_dir, 0777, true);
            chmod($docs_dir, 0777);
        }

        $new_dir = move_uploaded_file($tmp_name, $docs_dir.$file_name);
        $docs_url = F_WS_PATH_USER_PHOTOS."files/docs/".$_FILES["attachment_file"]["name"][$i];

        
     
        
        query("INSERT INTO orders_documents SET
        id = NULL,
        date_added = now(),
        site_id =".forsql($_SESSION["SA"]["site_id"]).",
        order_id =".forsql($order_id).",
        doc_type =".forsql($_FILES["attachment_file"]["type"][$i]).",
        doc_url =".forsql($docs_url).",
        doc_id =".forsql('1').",
        doc_name =".forsql($_FILES["attachment_file"]["name"][$i]));
    }

i also tried to insert 3 files "random.pdf","alter_tables.txt","testfile.txt" and simply check if all files are stored in $_FILE variable like:

print_r($_FILES);
        exit();

but the answer i get is:

    Array
(
    [attachment_file] => Array
        (
            [name] => testfile.txt
            [type] => text/plain
            [tmp_name] => C:\xampp\tmp\phpB3DC.tmp
            [error] => 0
            [size] => 150
        )
)

and like i said i get record in db and directory only of this file but not the other 2 ?

i tryed to add [] to the input name but nothing changed ? i litteraly dont know what else should i try to check why store only last one file in $_FILES

also the form have enctype="multipart/form-data"

CodePudding user response:

The name attribute of the input must show that you will receive an array. Change it to attachment_file[] to allow the array to be passed back to your server.

<input id="attachment_file" name="attachment_file[]" type="file" value="<?=$_POST["attachment_file"]?>"  multiple />
  • Related