Notice of undefined offset when upload csv file

<?php
include 'config.php';

if(isset($_POST['btn-uploadsf']))
{    
      $name = $_FILES['file']['name'];
	      $site = $_POST["site"];
	          $check=mysqli_query($db,"select * from nov where site='$site' AND f_name='$name'");
    $checkrows=mysqli_num_rows($check);

   if($checkrows>0) {
	   ?>
  <script>
  alert('Data is exist in database');
        window.location.href='index.php?fail';
        </script>;
    <?php
   } else { 
    //validate whether uploaded file is a csv file
    $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,site,name, cpu_count, memory_size, disk_space_size, nic_count, power_state) VALUES ('".$name."','".$site."','".$line[0]."','".$line[1]."','".$line[2]."','".$line[3]."','".$line[4]."','".$line[5]."')");
                }
            
	 
 ?>
  <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
 }
	  
	}
   //close opened csv file
            fclose($csvFile);


}
?>

Open in new window


The upload actually work just got the notice of the Notice of undefined offset , can fix the notice error ?
error.PNG
Yong Scott Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Dave BaldwinFixer of ProblemsCommented:
One of the items in your $line[] array doesn't exist, usually the last one.  Check your CSV file to see if it is actually there.
0
Julian HansenCommented:
Post a sample of the CSV file causing the error.
0
Yong Scott Author Commented:
Post a sample of the CSV file causing the error.
I will post soon .. because my csv file got 160 rows then will display that notice , if i import csv files with few rows then its fine without the notice
0
The Five Tenets of the Most Secure Backup

Data loss can hit a business in any number of ways. In reality, companies should expect to lose data at some point. The challenge is having a plan to recover from such an event.

Chris StanyonWebDevCommented:
It's already been pointed out, but it sounds like it's reading a line from your CSV that doesn't match what you expect (6 columns in your case). You should always run some validation / sanity checks before inserting to your database.

while(($line = fgetcsv($csvFile)) !== FALSE){
     // check $line here for any issues
     if ( count($line) != 6 ) continue;

     //insert member data into database
     $db->query("INSERT INTO nov(f_name,site,name, cpu_count, memory_size, disk_space_size, nic_count, power_state) VALUES ('".$name."','".$site."','".$line[0]."','".$line[1]."','".$line[2]."','".$line[3]."','".$line[4]."','".$line[5]."')");
}

Open in new window

You can make the check as simple or complicated as you need. The code above simply checks to make sure that $line contains 6 elements. If it doesn't, it skips to the next iteration, ignoring the DB call.
1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Julian HansenCommented:
I am not sure that skipping the line if it does not pass muster is the best course of action. You might want to see why the record failed and potentially correct it.
0
Yong Scott Author Commented:
The records actually uploaded well , just get the notice of undefined ofset .
0
Yong Scott Author Commented:
After  i try
while(($line = fgetcsv($csvFile)) !== FALSE){
     // check $line here for any issues
     if ( count($line) != 6 ) continue;

     //insert member data into database
     $db->query("INSERT INTO nov(f_name,site,name, cpu_count, memory_size, disk_space_size, nic_count, power_state) VALUES ('".$name."','".$site."','".$line[0]."','".$line[1]."','".$line[2]."','".$line[3]."','".$line[4]."','".$line[5]."')");
}
There no more notice happen
0
Yong Scott Author Commented:
I am not sure that skipping the line if it does not pass muster is the best course of action. You might want to see why the record failed and potentially correct it.
Isit there another better way to solve it ?
0
Chris StanyonWebDevCommented:
Like I said, you can make the checks as simple or as complicated as you like. If the line is blank, then the count($line) will equal 0. If that's the case, then the only logical course of action is to skip the line.

If there are more or less than 6 columns then you could try and apply some other logic, although it may not be possible. For example, if you have less than 6 columns in a line, how do you figure out which column is missing? If there are more than 6, do you just use the first 6?

Ultimately you don't want bad data in your DB, so if there's any doubt about the integrity of a record, personally, I'd skip it (and maybe log the duff line)
0
Julian HansenCommented:
The records actually uploaded well , just get the notice of undefined ofset .
Because one (or more) of the records was badly formed. You might want to know why it was badly formed and address that issue.
This is why I asked to see a version of the CSV file so we can better understand why it is failing - ignoring the error will make your program run but it is probable that it will have undesirable side effects.
0
Julian HansenCommented:
Isit there another better way to solve it ?
Write it to a log file
define('LOGFILE','path/to/logfile.log');
...
$line = 0;
while(($line = fgetcsv($csvFile)) !== FALSE){ 
  $line++;
  if ( count($line) != 6 ) {
    file_put_contents(LOGFILE, "Line {$lineno} failed: {$line}\n", FILE_APPEND);
    continue;
  }
 ...
}

Open in new window

0
Yong Scott Author Commented:
Write it to a log file
where to check the log file then?
0
Julian HansenCommented:
Where ever it is convenient for you. It does not make a difference you just want it were it is accessible so you can check it for errors.

Common practice is the web-root - if you do this you might want to prevent direct access to it using .htaccess rules as you could be exposing sensitive data (I don't know what your data is but it is something to bear in mind).

Alternatively you can locate it outside of the web-root which will also secure it from external access.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.