Reputation: 75
At the moment I am able to get data from a CSV file called "data.csv" which I manually uploaded to the web server. I am able to then upload the data to database and this all works fine.
What I need to be able to do is:
Code Below:
upload.php
<?php
include('config.php');
$file = "data.csv";
$separator = ",";
$length = 0;
$fields = array('title', 'firstName', 'secondName', 'emailAddress', 'houseNumber', 'mobileNumber', 'address1', 'address2', 'address3', 'address4', 'postcode');
$handle = fopen($file, "r");
$header = array_flip(fgetcsv($handle, $length, $separator));
$values = array();
$i = 1;
while(($csvData = fgetcsv($handle, $length, $separator)) !== false){
$values = array();
echo $i." - You have inserted another row of data into the database.<br>";
foreach ($fields as $field){
$values[] = $csvData[$header[$field]];
}
mysql_query("INSERT INTO csv (" . implode(',', array_keys($header)) . ") VALUES ('" . implode("','", $values) . "')");
$i++;
}
fclose($handle);
?>
Please ask if I haven't quite explained this properply.
Thanks in advance.
Upvotes: 0
Views: 3619
Reputation: 24645
The Following should be a complete solution for you.
In your html
<form enctype="multipart/form-data" action="sompepage.php" method="POST">
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<!-- Name of input element determines name in $_FILES array -->
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
In PHP (somepage.php)
<?php
include('config.php');
$file = $_FILES['userfile']['tmp_name'];
$separator = ",";
$length = 0;
$fields = array('title', 'firstName', 'secondName', 'emailAddress', 'houseNumber', 'mobileNumber', 'address1', 'address2', 'address3', 'address4', 'postcode');
$handle = fopen($file, "r");
$header = array_flip(fgetcsv($handle, $length, $separator));
$values = array();
$i = 1;
while(($csvData = fgetcsv($handle, $length, $separator)) !== false){
$values = array();
echo $i." - You have inserted another row of data into the database.<br>";
foreach ($fields as $field){
$values[] = $csvData[$header[$field]];
}
$values = array_map("mysql_real_escape_string", $values);
mysql_query("INSERT INTO csv (" . implode(',', $fields) . ") VALUES ('" . implode("','", $values) . "')");
$i++;
}
fclose($handle);
?>
Upvotes: 2