Jump to content

php noob needs help importing csv to db, empty array causing mysql error


sigkill-9

Recommended Posts

I'm new to PHP, am in an advanced PHP class in college and working on a project that requires importing a comma separated list of users into a mysql db but I'm having an issue with the import and need some help.

 

The import function works, E.G it imports the users into the db successfully, however, when the function gets to the end of the CSV file it adds an empty array and, of course, gives me a mysql error because of the null entries in the last array.

 

I'm trying to figure out how to eliminate the empty arrays from the multidimensional array $lineItem2, have been working on it all day, but the solution eludes me.

 

First, this is what the array looks like after its imported and processed:

(note the empty array at bottom)

Array(
     [0] => Array(
             [fname] => Todd
             [lname] => Preston
             [email] => tpreston@somewhere.com)
  
     [1] => Array(
             [fname] => Sam
             [lname] => Phillips
             [email] => sphillips@somewhere.net)
  
     [2] => Array(
             [fname] =>
             [lname] =>
             [email] => )
)

 

I'm not familiar with importing files to db's, this is my first attempt.

Here's the entire code I'm using to read from and proccess the file:

require 'import.php'; //db model, contains user_import function

$import = new userAdmin;

if (isset($_FILES['uploadedfile'])) {
    $inFile = fopen($_FILES['uploadedfile']['tmp_name'], "r");
    $myData = fread($inFile, filesize($_FILES['uploadedfile']['tmp_name']));
    fclose ($inFile);
    $myDB = split("\n", $myData);

    //split each line by comma values
    foreach($myDB as $data){
        $lineItem[] = split(",", $data);
    }

    //create array for db import
    foreach($lineItem as $key){
        $lineItem2[] = array('fname' => $key[0],
                                     'lname' => $key[1],
                                     'email' => $key[2]);
    }

    //remove empty arrays from $lineItem2
    foreach($lineItem2 as $key => $value){
         //fname is the first value in each array, if it's empty, drop it.
         if($value['fname'] === ''){
            unset($key); //not working
         }
  
         //set values for db insertion
         $fname = $value['fname'];
         $lname = $value['lname'];
         $email = $value['email'];
  
         //insert new array values into db
         $import->import_users($fname,$lname,$email);
    }
}

 

Any help would be greatly appreciated, thanks  8)

Link to comment
Share on other sites

You can change:

         //set values for db insertion
         $fname = $value['fname'];
         $lname = $value['lname'];
         $email = $value['email'];

         //insert new array values into db
         $import->import_users($fname,$lname,$email);

 

to

 

         //set values for db insertion
         $fname = trim($value['fname']);
         $lname = trim($value['lname']);
         $email = trim($value['email']);
         
         // make sure all fields are NOT empty.
         if ($fname !== '' && $lname !== '' && $email !== '') {
                  //insert new array values into db
                  $import->import_users($fname,$lname,$email);
         }

Link to comment
Share on other sites

<?php
$file = "/path/to/csv/file";
$contents = file( $file );
$records = array();
foreach( $file as $line ) {
  $line = trim( $line );
  if( !strlen( $line ) ) { continue; } // ignore empty lines
  if( substr_count( $line, ',' ) != 2 ) { continue; } // expect 2 commas
  list( $fname, $lname, $email ) = explode( ',', $line );
  $records[] = array( 'fname' => $fname, 'lname' => $lname, 'email' => $email );
}
print_r( $records ); // should have no empty records
?>

 

Or you could probably just load it directly from the CSV file with and not use PHP at all:

http://dev.mysql.com/doc/refman/5.1/en/load-data.html

 

Sure, you're taking a PHP class.  But no sense catching a fish with dynamite if you have a pole handy.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.