PHP MySQL – Import CSV Using LOAD DATA INFILE – Determine file path


I need some help connecting the dots on this. There's plenty of snippets floating around but I haven't found a good end to end tutorial.

For a simple custom CMS I'm building I want an option for end user admins to upload a CSV of other users. PHPMyAdmin or other "direct" access to the DB is not an option for my environment. So I'm trying to build a file upload form that then inserts the data in to the appropriate table.

I found this tutorial on building the upload form – working fine (although I'd like to add some additional validation/security). And based on these several posts here (like this one) I think that using LOAD DATA INFILE makes more sense than trying to loop and parse with fgetcsv or something (but feel free to disagree).

Here's my current code – it's not working and I assume it's the file path – how should I format it? The _uploads directory is in the same place as this processor file.

$target_path = "_uploads/";

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name']). 
    " has been uploaded to " . $target_path;
} else{
    echo "There was an error uploading the file, please try again!";

$sql = "LOAD DATA INFILE $target_path
        INTO TABLE User
        (UserFirstName, UserLastName)
        LINES TERMINATED BY '\r\n'

$result = mysql_query($sql, $connection);

if (mysql_affected_rows() == 1) {
    $message = "The user was successfully updated!";
} else {
    $message = "The user update failed: ";
    $message .= mysql_error(); 

echo $message;

Any suggestions or pointers to decent tutorials would be appreciated.

Best Solution

Your problem is that PHP is working on the webserver, MySQL is working on the database server. I think as long as no replication is involved the missing "dot" could be


to read from the client-computer.


as of 2018:

Related Question