Question

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)
        FIELDS TERMINATED BY ',' ENCLOSED BY '\"' ESCAPED BY '\"'
        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.

Was it helpful?

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

LOAD DATA LOCAL INFILE

to read from the client-computer.

(original: http://dev.mysql.com/doc/refman/5.1/de/load-data.html)

as of 2018: https://dev.mysql.com/doc/refman/8.0/en/load-data.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top