Avatar of Yong Scott
Yong ScottFlag for Malaysia asked on

I upload file from directory to database but i realise that all file i upload is the same.

How to fix this .. can upload the directory but all the csv file content i upload was the same file  ..
Actually there are 30 files , but one file uploaded 30 times.
Here are my code for upload part .. upload.php
<?php
include 'config.php';

if(isset($_POST['btn-upload']))
{    
  $log_directory = '/xampp/htdocs/mydoc';
  $results_array = array();

        if ($handle = opendir($log_directory))
        {
                while(($file = readdir($handle)) !== FALSE)
                {
                    if ($file != "." && $file != "..") {
                        $results_array[] = $file;
                    }
                }
                closedir($handle);
        }

  //Output findings
  foreach($results_array as $value)
{
 $csvMimes = array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain');
    if(!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'],$csvMimes)){
        if(is_uploaded_file($_FILES['file']['tmp_name'])){
            
            //open uploaded csv file with read only mode
            $csvFile = fopen($_FILES['file']['tmp_name'], 'r');
            
            //skip first line
            fgetcsv($csvFile);
            
            //parse data from csv file line by line
            while(($line = fgetcsv($csvFile)) !== FALSE){
                 //insert member data into database
                    $db->query("INSERT INTO nov(f_name,name, cpu_count, memory_size, disk_space_size, nic_count, power_state) VALUES ('".$value."','".$line[0]."','".$line[1]."','".$line[2]."','".$line[3]."','".$line[4]."','".$line[5]."')");
                }
            }
            			
            //close opened csv file
            fclose($csvFile);


        


 if(move_uploaded_file)
 {
	 
 ?>
  <script>
  alert('successfully uploaded');
        window.location.href='index.php?success';
        </script>
  <?php
 }
 else
 {
  ?>
  <script>
  alert('error while uploading file');
        window.location.href='index.php?fail';
        </script>
		
  <?php
 }
}
}
}

?>

Open in new window

DatabasesPHP

Avatar of undefined
Last Comment
Julian Hansen

8/22/2022 - Mon
Julian Hansen

I am guessing you used a multiple file input but did not specify an array as the name for the control

In other words
<input type="file" multiple" name="file">

Open in new window

Instead of
<input type="file" multiple" name="file[]">

Open in new window


Note the [] on the end of the name - this will create names for the uploaded files that PHP will translate into an array.

Post your HTML form so we can see how you have implemented that.

If you use the above you will get a response that looks something like this
$_FILES
   name: Array()
      0 => Filename1.csv
      1 => Filename2.csv
      ...
    tmp_name: Array()
      0: d9dwe99x.tmp
      1: eix9d9b9d.tmp
       ...
     size: ...

Open in new window


In other words an array of N items for each of the attributes for a file upload - where N is the number of files uploaded.

You will then need to create a loop that operates on these arrays - checking the file is uploaded and then moving / renaming them to their new location before updating the DB.

Post your <form> code so I can confirm the above.
ASKER
Yong Scott

<?php
include 'config.php';
?>
<!DOCTYPE html>
<html>
<head>
<title>File Uploading With PHP and MySql</title>

<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="header">
<label>File Uploading With PHP and MySql</label>
</div>
     <br /><br />
   <form action="index.php" method="post" enctype="multipart/form-data">
   <button type="submit" name="btn-main" style="height: 25px; width: 200px">MAIN PAGE</button>
    </form>

<div id="body">

<table style = "border-collapse:collapse">
    <tr>

    </tr>
    <tr>
                <thead>
                    <tr>
					  <th style = "width:20px;border:1px solid black" align = "center">Date</th>
                      <th style = "width:20px;border:1px solid black" align = "center">File Name</th>
                      <th style = "width:20px;border:1px solid black" align = "center">Site</th>					  
                      <th style = "width:20px;border:1px solid black" align = "center">Name</th>
                      <th style = "width:20px;border:1px solid black" align = "center">CPU Count</th>
                      <th style = "width:20px;border:1px solid black" align = "center">Memory Size</th>
                      <th style = "width:20px;border:1px solid black" align = "center">Disk Space Size</th>
                      <th style = "width:20px;border:1px solid black" align = "center">NIC Count</th>
					  <th style = "width:20px;border:1px solid black" align = "center">Power State</th>
                      <th style = "width:20px;border:1px solid black" align = "center">Memory Size(inGB)</th>
					  <th style = "width:20px;border:1px solid black" align = "center">Disk Space Size(inGB)</th>
                    </tr>
                </thead>
                <tbody>
                <?php
                    //get records from database
                    $query = $db->query("SELECT * FROM nov");
                    if($query->num_rows > 0){ 
                        while($row = $query->fetch_assoc()){ ?>
                    <tr>

                      <td style = "width:20px;border:1px solid black" align = "center"><?php echo date('m-d-y', strtotime($row['date'])); ?></td>	
					  <td style = "width:20px;border:1px solid black" align = "center"><?php echo $row['f_name']; ?></td>	
					  <td style = "width:20px;border:1px solid black" align = "center"><?php echo $row['site']; ?></td>					  
                      <td style = "width:20px;border:1px solid black" align = "center"><?php echo $row['name']; ?></td>
                      <td style = "width:20px;border:1px solid black" align = "center"><?php echo $row['cpu_count']; ?></td>
                      <td style = "width:20px;border:1px solid black" align = "center"><?php echo $row['memory_size']; ?></td>
                      <td style = "width:20px;border:1px solid black" align = "center"><?php echo $row['disk_space_size']; ?></td>
					  <td style = "width:20px;border:1px solid black" align = "center"><?php echo $row['nic_count']; ?></td>
					  <td style = "width:20px;border:1px solid black" align = "center"><?php echo $row['power_state']; ?></td>
					  <td style = "width:20px;border:1px solid black" align = "center"><?php echo $row['memory_size_ingb']; ?></td>
					  <td style = "width:20px;border:1px solid black" align = "center"><?php echo $row['disk_space_size_ingb']; ?></td>
                      
                    </tr>
                    <?php } }else{ ?>
                    <tr><td style = "width:20px;border:1px solid black" align = "center" colspan="12">No data(s) found.....</td></tr>
                    <?php } ?>
 
    </table>
    

</div>
</body>
</html>

Open in new window

ASKER
Yong Scott

That is my html code
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
ASKER
Yong Scott

Do you know how to not target directory can upload file which mean all directory can access no specific directory?
Julian Hansen

Where is your file input control?
ASKER
Yong Scott

   <font size="5">Directory Upload</font>
      <br /><br />
 <form action="upload.php" method="post" enctype="multipart/form-data">
 <input type="file" webkitdirectory mozdirectory  name="file"  />
 <button type="submit" name="btn-upload" style="height: 25px; width: 100px">UPLOAD</button>
 </form>

Open in new window

Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Julian Hansen

webkitdirectory and mozdirectory are non-standard attributes - they are not part of the HTML5 standard and are not supported in all browsers.

Do you know how to not target directory can upload file which mean all directory can access no specific directory?
I have no idea what this is saying
ASKER
Yong Scott

webkitdirectory and mozdirectory are non-standard attributes - they are not part of the HTML5 standard and are not supported in all browsers.
Its can work in my browser , only problem is the directory file uploaded but all file is the same
ASKER
Yong Scott

Actually I want to upload folder that contains of csv files , but the files have different data inside , so how can I display it all
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
ASKER
Yong Scott

Unfortunately, it only works for a single file insertion. I have further tried to edit it, but it just inserts the last file that is in the directory. Any help will be much appreciated.
Julian Hansen

Where is your code that iterates over the files variable to get all the files and save them
When you submit multiple files they are put in an array that looks like this
Array
(
  [files] => Array
    (
      [name] => Array
        (
          [0] => 01.csv
          [1] => 02.csv
          [2] => 03.csv
          [3] => 04.csv
          [4] => 05.csv
        )
      [type] => Array
        (
          [0] => application/vnd.ms-excel
          [1] => application/vnd.ms-excel
          [2] => application/vnd.ms-excel
          [3] => application/vnd.ms-excel
          [4] => application/vnd.ms-excel
        )
      [tmp_name] => Array
        (
          [0] => C:\Windows\Temp\php5FEB.tmp
          [1] => C:\Windows\Temp\php5FEC.tmp
          [2] => C:\Windows\Temp\php5FED.tmp
          [3] => C:\Windows\Temp\php5FEE.tmp
          [4] => C:\Windows\Temp\php5FEF.tmp
        )
      [error] => Array
        (
          [0] => 0
          [1] => 0
          [2] => 0
          [3] => 0
          [4] => 0
        )
      [size] => Array
        (
          [0] => 170516
          [1] => 116832
          [2] => 2351
          [3] => 275819
          [4] => 1870
        )
    )
)

Open in new window


I have already given you the process for iterating over this array in this comment (in your other question)
https://www.experts-exchange.com/questions/29078470/How-to-import-directory-and-echo-the-filename.html#a42435985
ASKER
Yong Scott

Array
(
  [files] => Array
    (
      [name] => Array
        (
          [0] => 01.csv
          [1] => 02.csv
          [2] => 03.csv
          [3] => 04.csv
          [4] => 05.csv
        )
      [type] => Array
        (
          [0] => application/vnd.ms-excel
          [1] => application/vnd.ms-excel
          [2] => application/vnd.ms-excel
          [3] => application/vnd.ms-excel
          [4] => application/vnd.ms-excel
        )
      [tmp_name] => Array
        (
          [0] => C:\Windows\Temp\php5FEB.tmp
          [1] => C:\Windows\Temp\php5FEC.tmp
          [2] => C:\Windows\Temp\php5FED.tmp
          [3] => C:\Windows\Temp\php5FEE.tmp
          [4] => C:\Windows\Temp\php5FEF.tmp
        )
      => Array
        (
          [0] => 0
          [1] => 0
          [2] => 0
          [3] => 0
          [4] => 0
        )
      [size] => Array
        (
          [0] => 170516
          [1] => 116832
          [2] => 2351
          [3] => 275819
          [4] => 1870
        )
    )
)
So I need list down the file for each array?
something like this :
          [0] => file1.csv
          [1] => file2.csv
          [2] => file3.csv
          [3] => file4.csv
          [4] => file5.csv
Until file30.csv?
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER CERTIFIED SOLUTION
Julian Hansen

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER
Yong Scott

Im sorry Julian not so understand ur coding :(
Julian Hansen

What don't you understand?
ASKER
Yong Scott

I tried to implement your coding ..
<?php
include 'config.php';


if(isset($_POST['btn-upload']))
{  


$targetDir = "uploads/";
$files = $_FILES['file']
foreach($files['name'] as $key => $name) {
    $file = $files['tmp_name'][$key];
    $target = $targetDir  . "/" . $name;
    if (is_uploaded_file($file)) {
       move_uploaded_file($file, $target);
echo $file . '</br>';
   
    }
}
}

?>	

Open in new window

I not sure is it the right way , but the output get error .


Parse error: syntax error, unexpected 'foreach' (T_FOREACH) in C:\xampp\htdocs\db_v3\upload.php on line 11
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
Julian Hansen

You are missing a ';' on line 10
$files = $_FILES['file']

Open in new window

Should be
$files = $_FILES['file'];

Open in new window

ASKER
Yong Scott

Parse error: syntax error, unexpected 'foreach' (T_FOREACH) in C:\xampp\htdocs\db_v3\upload.php on line 11
still have this error
Julian Hansen

Please don't post errors without the accompanying source code. I have no idea what your code now looks like and the error on its own is of no use.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER
Yong Scott

<?php
include 'config.php';


if(isset($_POST['btn-upload']))
{  


$targetDir = "uploads/";
$files = $_FILES['file'];
foreach($files['name'] as $key => $name) {
    $file = $files['tmp_name'][$key];
    $target = $targetDir  . "/" . $name;
    if (is_uploaded_file($file)) {
       move_uploaded_file($file, $target);
echo $file . '</br>';
   
    }
}
}

?>	

Open in new window

This my coding
ASKER
Yong Scott

$targetDir = "uploads/";

Open in new window

anyway the "uploads/" is nid to set path ?
ASKER
Yong Scott

Thank Julian Hansen ! I tried your code and success already
Your help has saved me hundreds of hours of internet surfing.
fblack61
Julian Hansen

You are welcome.