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
Scott Yong Asked:
Who is Participating?
 
Chris StanyonConnect With a Mentor Commented:
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
 
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
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

 
Scott Yong 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
 
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
 
Scott Yong Author Commented:
The records actually uploaded well , just get the notice of undefined ofset .
0
 
Scott Yong 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
 
Scott Yong 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 StanyonCommented:
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
 
Scott Yong 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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.