0

Trying to use 'LOAD DATA INFILE' in order to populate a database table from a CSV(10k records) but at the moment it does nothing.

No error, no data being input and I have no idea what is wrong with it so any help is appreciated!

My code (-CSS and DBconnect):


if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
    echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded
   successfully." . "</h1>";
}

$temp_file = $_FILES['filename']['tmp_name']; 
$origin_file = $_FILES['filename']['name'];
$target_file = 'uploads/'.$origin_file;
move_uploaded_file($temp_file, $target_file);
$file_name = $target_file;

$query = <<<eof
LOAD DATA LOCAL INFILE '$file_name'
 INTO TABLE importing
 FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '"'
 LINES TERMINATED BY '\n'
(text,number)
IGNORE 1 LINES
eof;

mysql_query($query);


print "Import done";

mysql_close(); 
//view upload form
}else {

print "Upload new csv by browsing to file and clicking on Upload<br />\n";

print "<form enctype='multipart/form-data' action='upload.php' method='post'>";

print "File name to import:<br />\n";

print "<input size='50' type='file' name='filename'><br />\n";

print "<input type='submit' name='submit' value='Upload'></form>";
0

1 Answer 1

2

Note

Please, don't use mysql_* functions for new code. They are no longer maintained and the community has begun the deprecation process. See the red box? Instead you should learn about prepared statements and use either PDO or MySQLi. If you can't decide, this article will help to choose. If you care to learn, here is good PDO tutorial.

To see what error your code outputs change

mysql_query($query);

to

$result = mysql_query($query);
if (!$result) {
    die('Invalid query: ' . mysql_error());
}

Then mysql_error() will output the error instead of just nothing ...

As pointed out by @Lèsemajesté - move_uploaded_file() also returns a boolean which you should check is true :

Returns TRUE on success.

If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.

If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return FALSE. Additionally, a warning will be issued.

Full docs for move_uploaded_file() here

Sign up to request clarification or add additional context in comments.

2 Comments

To be safe, he should probably do the same with move_uploaded_file() as well.
Thanks! I'll go convert it to MySQLi now :) turned out that it was "(text,number)" causing the problem in my query

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.