Isaías Sosa
Isaías Sosa

Reputation: 113

How to solve a Undefined offset when reading a csv file with PHP.?

Hello to all so kind persons who are always there to help us. I need to importa a csv file to mysql using php. the code I have until now is as follows:

Steps: make all the corresponding validations. make a mysql connection.

 //process the csv file
   $handle = fopen($_FILES['file']['tmp_name'], "r");
   while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
    $att0 = mysql_real_escape_string($data[1]);
    $att1 = mysql_real_escape_string($data[1]);
    $att2 = mysql_real_escape_string($data[2]);
        etc, etc.
   $sql = "INSERT INTO Alumnos etc, etc.";
   mysql_query($sql);

Error: Notice: Undefined offset: 1 in D:\www\studentAdministrator\imports\importar1.php on line 58

I'll appreciate any help. thanks in advance.

I Solved my problem. I changed the semicolon by comma I appreciate the answers that have already posted

Upvotes: 2

Views: 3172

Answers (2)

Fluffeh
Fluffeh

Reputation: 33542

Check your variables before they are passed and used like this:

if(isset($data[1]))? $att0 = mysql_real_escape_string($data[1]) : $att0='null';

You can set it to whatever you like, just thought you might be able to see the NULL nice and easy that way.

If you know that the CSV file will have columns missing, but always in the right order (probably not a great example in this scenario, but worth mentioning) you can also do something like this:

for($i=0;$i<count($data);$i++)
{
    echo 'Value '.$i.' is: '.$data[$i].'\n';
}

This will parse through however many items there are per line and you can use them without worrying about the number. Again, in your scenario, probably not the best, but worth mentioning.

Upvotes: 1

octern
octern

Reputation: 4868

As I said in my comment, this may be caused by exporting a line that has blank cells at the end. Some utilities will end the line after the last cell, instead of putting in the appropriate number of delimiters. Check your file, and if that's the problem, you can just add a little logic to your script to deal with it -- check isset() for each index before you try to use it, and if it doesn't exist, substitute an empty string (or null, or whatever you use for an empty cell elsewhere in the file).

Upvotes: 1

Related Questions