简体   繁体   中英

Using html form to import csv data… using PHP script load data infile and MySQL

I'm having trouble getting this script to work running on a MAMP local server:

<?php
//Uploader Script for mass upload of devices.
//Check for errors
if($_FILES['file_upload']['error'] > 0){
    die('An error ocurred when uploading.');
}
//check file type is csv
if($_FILES['file_upload']['type'] != 'text/csv'){
    die('Unsupported filetype uploaded.');
}
//check size of csv
if($_FILES['file_upload']['size'] > 500000){
    die('File uploaded exceeds 500kb - maximum upload size.');
}
$file_url = $_FILES['file_upload']['tmp_name'];
$query = <<<eof
    LOAD DATA LOCAL INFILE '$file_url'
     REPLACE
     INTO TABLE DEVICE
     FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
     LINES TERMINATED BY '\n'
    (device_id, device_name, app_name)
eof;

$load_data = mysql_query($query);

The data is going into a single table with no foreign key dependencies. I'm trying to upload a CSV and have been successfully using the database with other code. I'm using this email form:

<form action='upload.php' enctype='multipart/form-data'  method='post'>";
     File: <input type='file' name='file_upload'>"; 
     <input type='submit' name='Submit' value='Download Devices' />
 </form>

I think that you need to add enctype="multipart/form-data" to your form tag.

See What does enctype='multipart/form-data' mean?

OK so now we know that's in there, you need to check that the user running the MySQL process has permission to access the temporary file at $_FILES['file_upload']['tmp_name']. This is the most likely point of failure.

You might be able to find this using mysql_error or mysql_errno functions: http://php.net/mysql_error

$load_data = mysql_query($query)  or die("<b>A fatal MySQL error occured</b>.\n<br />Query: " . $query . "<br />\nError: (" . mysql_errno() . ") " . mysql_error()); 

This will let you know if mysql failed and output why.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM