Peter
Peter

Reputation: 13

PHP Load Data Infile not working

I am still newbie here. I am trying to use mysql LOAD DATA INFILE on php script to load csv file. It neither gives any error nor it loads any data. Can anyone please help me out? I am using following php code

<?php

$db1=mysql_connect('localhost', 'root', '');
mysql_select_db('student',$db1);

$query = "LOAD DATA INFILE 'mysqlresults.csv' INTO TABLE student.student_info FIELDS TERMINATED BY ','";

$result = mysql_query($query);
if ($result == true){
echo 'success';
}
else{
echo 'not success';
}
?>

Upvotes: 0

Views: 5759

Answers (2)

Remko Janse
Remko Janse

Reputation: 36

You need to set the path to your file

LOAD DATA LOCAL INFILE '/path/to/your/local/file' INTO TABLE 

mysql does not look in the same position as the php script is run from, as mysql will then look in its own path location, and will not find the file (cause it's somewhere else).

You can use __DIR__ in php to get the current location php is running it, so the query would look like $query = "LOAD DATA INFILE ". __DIR__ . DIRECTORY_SEPARATOR . "'mysqlresults.csv' INTO TABLE student.student_info FIELDS TERMINATED BY ','";

The DIRECTORY_SEPARATOR is cause DIR does not have a trailing slash

Upvotes: 2

axiac
axiac

Reputation: 72376

Your PHP code uses a MySQL extension as a client for the MySQL server. The two components (PHP and MySQL server) many times run on different computers.

LOAD DATA INFILE loads the data from a CSV file that is located on the computer that runs the MySQL server.

I suppose your file is located on the computer that runs the PHP script (i.e. on the computer that runs the MySQL client).

The LOCAL option of the LOAD DATA INFILE command tells the MySQL client to load the data from a file on the computer where it runs (the "local" computer) and send it to the server for loading.

For both versions of the command, if the file name does not contain a path, the MySQL client or server uses its configuration to know where to search the file (and it turns out that it usually cannot find it there because the developer doesn't know/care about that config and puts the file somewhere else).

The solution is quite simple: always use the absolute path of the file. If the file is local (this happens in 99.99% of the cases when PHP is involved) then you can use the PHP magic constant __DIR__ and the function dirname() to build the absolute path of the CSV file starting from the location of the script that contains the code.

From your code it seems the CSV file is located in the same directory as the PHP file(s) (this is not a good practice). The code should be something like:

$path = __DIR__.'/mysqlresults.csv';
$query = "LOAD DATA LOCAL INFILE '$path' INTO TABLE student.student_info FIELDS TERMINATED BY ','";

Upvotes: 0

Related Questions