I'm fairly new to PHP (6 mo exp), am in a 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 tries to import 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 array from $lineItem2, but the solution eludes me. I'm not familiar with importing files to db's, this is my first attempt. I realize there may be an easier, more efficient way to do this, and if so I'm open to suggestions.
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] => )
)
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)