I've been trying this for a while and investigating as many avenues as I could before asking my first questions here.
I have a very simple csv file. One column, data separated by linux line feeds. I want to import it into the 2nd column (passcode) of a table (codes). The first column is a primary key auto incrementing.
Here's the simple csv data (linux line feeds - \n)
A12345678911
A12345678912
A12345678913
A12345678914
Here's the form to gather the file.
<form enctype="multipart/form-data" action="upload_webcodes.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<input type="hidden" name="success" value="success" />
Send this file: <input name="webcodeupload" type="file" />
<input type="submit" value="Send File" />
</form>
Here's the php which is attempting to run the query to load the tmp file into the database.
<?php
function dbconnect(){
$db = mysql_connect('localhost', 'root', 'root');
mysql_select_db("mydatabase", $db);
return $db;
}
if ($_FILES['upload']['type'] === 'text/csv') {
$database = dbconnect();
$getfile = $_FILES['upload']['tmp_name'];
$sql = " LOAD DATA LOCAL INFILE $getfile INTO TABLE codes (`passcode`) LINES TERMINATED BY '\n' ";
mysql_query($sql);
}
?>
I can't get it to work. I'm trying this locally with MAMP. The /tmp/php folder Date Modified gets updated but I can't see a file there. I've even tried larger files since my test file is so simple. I have printed out the $_FILES array after submitting the form.
Array
(
[webcodeupload] => Array
(
[name] => Aimport.csv
[type] => text/csv
[tmp_name] => /Applications/MAMP/tmp/php/phpsp9ezx
[error] => 0
[size] => 52
)
)
It seems that the expected results are there? I've tried the query in phpmyAdmin and it works if I remove the LINES TERMINATED BY clause. I suspect that's a phpmyAdmin thing, and i've also tried this code with and without that clause in the query.
Additionally there are a few "undefined index" errors when loading the page. I sort of understand why, and have read threads here indicating ways to mask the errors, but I'd be interested in knowing how to avoid them rather than hide them.
Any input would really be appreciated.
Thanks.
mysql_query()
. the load query's probably failing, but you're not capturing any return values, which means you've simply assumed it all succeeded. at minimum:$result = mysql_query(...) or die(mysql_error())
. – Marc B Feb 8 at 21:14