Jump to content

CSV Import from webhost to different db server


Donovan

Recommended Posts

I have a process where I need to upload a csv file to import to a MySQL database.  The webserver and db are not on the same server.  I think the  problem is that the db  cannot see the temp file that gets uploaded to /private/var/ webserver so it fails to import using $sql = "LOAD DATA INFILE

 

I was going to try and physically upload the file to a uploadcache directory on the webserver, such as

 

$fileName = basename($_FILES['file_source']['name']);		
move_uploaded_file($_FILES['file_source']['tmp_name'], $uploadFolder.$fileName);

 

then define a path such as

 

$uploadServer = $_SERVER["HTTP_HOST"];
$uploadFolder = $_SERVER['DOCUMENT_ROOT'] . "/atlas/modules/$modname/uploadcache/";

 

then try

 

$sql = "LOAD DATA INFILE '".$uploadServer."".$uploadFolder."".$fileName."'

 

but I don't think I have the concatenation correct.

 

is this possible?

 

Since it is only about 100 records I was also thinking of doing it like this.

 

$uploadServer = $_SERVER["HTTP_HOST"];
$uploadFolder = $_SERVER['DOCUMENT_ROOT'] . "/atlas/modules/$modname/uploadcache/";
$csvFile = 	$uploadServer.$uploadFolder.$fileName;
$csv = file_get_contents($csvFile);

$breaker = "\n";
$fields = array('ReportNumber', 'Student_ID', 'Name_Last', 'Name_First', 'Total_RS', 'Total_Percent', 'Percentile', 'Subtest_RS', 'Subtest_Percent');

$lines = explode($breaker, $csv);
$sql = "INSERT INTO `$table_name` ('" . implode(", '", $fields) . "') VALUES ";
$db->sql_query($sql);
if (!$sql) {echo("<p>Error performing query: " . mysql_error() . "</p>");} 
$i=0;
foreach($lines as $line)
{
  if($i>0 && ($i%100 == 0))
  {
    $query = substr($query, 0, -1); // Get rid of trailing comma
    $query .= ";
INSERT INTO `$table_name` ('" . implode("', '", $fields) . "') VALUES ";
  }

  $values = explode(',', $line);
  $query .= "
('" . implode("', '", $values) . "'),";
}

$result = $db->sql_query($query);	
if (!$result) {echo("<p>Error performing query: " . mysql_error() . "</p>");}
if(mysql_affected_rows() != count($lines))
  die('MySQL Insert failed to insert all entries.');
else
  header("Location: ".$admin_file.".php?op=TLScantronIratInsert&Session_ID=$Session_ID");
  }
  
?>

 

 

But am having a hard time understanding this code with arrays.

 

Specifically why he has two INSERT INTO statements.

 

 

 

 

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.