Home > Blockchain >  Php how read csv file data one by one?
Php how read csv file data one by one?

Time:02-25

I am uploading a CSV and while uploading I need to check one of its column lengths.

If column value length 3 then it should move the file into directory, otherwise the loop will break and show the message.

Currently it's showing the message but going into else condition also.

I want:

  • first it will check length of all values in csv column
  • if okay then move to upload csv.

e.g in csv file column values 1 to 15 are okay but on 16th row value is less then 3 then it's uploading file because 1 to 15 are correct and on 16th row it shows error message. But i need that first it check all values length of that column then proceed to move.

This is my code.

        while(($data = fgetcsv($handle)) !== FALSE) 
        {   
            $count  ;
            $itemCode=$data[3];
            if(strlen($invCode) >3 || strlen($invCode) <3)
            {
                
                echo $message = 'Error in length.';
                break;
            }else{
                
                continue;   
            }   
            
        }

        if (move_uploaded_file($_FILES["csv_file"]["tmp_name"], $target_file)) 
        {


        }   
        

CodePudding user response:

Your move_uploaded_file command is outside the loop, so it'll always be executed, no matter what happened within the loop.

To fix this, basically you need to set a flag in the loop (i.e. just a boolean variable) which can then be used at the end of the loop to indicate whether the validation was successful or not. If you have to break out of the loop because one of the lengths was wrong, then set the flag to false. Otherwise we can assume it was ok.

Also the code can be simplified a little bit in places, for readability, and there's a typo ($itemCode v.s. $invCode).

For example:

    $valid = true;

    while(($data = fgetcsv($handle)) !== FALSE) 
    {   
        $invCode = $data[3];

        if(strlen($invCode) != 3)
        {
            $valid = false;
            break;
        }   
    }

    if ($valid == true)
    {
      if (move_uploaded_file($_FILES["csv_file"]["tmp_name"], $target_file)) 
      {

      }
    } 
    else
    {
       echo $message = 'Incorrect inventory code used. Please check and reload';
    }
  • Related