Search code examples
phpmysqldatabaseload-data-infile

LOAD DATA INFILE - mysql/php script not functioning as it should


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>";

Solution

  • 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