How do I get a CSV file uploaded via an HMTL form to import using mysqli_query?

20 hours ago 3
ARTICLE AD BOX

But I can't find any details on how the HTML form is actually used to upload the file to where mysqli_query can import it.

You first need to know where mysqli_query can import it. Create a test CSV file there and verify mysqli_query can import it.

Next verify how you are handling the file upload:

$uploaded = $_FILES["fileupload"]["name"];

POST method uploads explains:

$_FILES['userfile']['name']
The original name of the file on the client machine.

Caution: Never use the 'name' provided by the user, that is a (huge) security risk. (more info below)

Apart from dangerous, that 'name' is merely informative (client machine = the computer of the user posting the form, the uploader), you need an actual pathname on the same system where you load the infile from:

$_FILES['userfile']['tmp_name']
The temporary filename of the file in which the uploaded file was stored on the server.

The uploaded file is temporary, see is_uploaded_file() for Example #1 is_uploaded_file() example.

if (is_uploaded_file($_FILES['userfile']['tmp_name'])) { echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n"; echo "Displaying contents\n"; readfile($_FILES['userfile']['tmp_name']); } else { echo "Possible file upload attack: "; echo "filename '". $_FILES['userfile']['tmp_name'] . "'."; }

This example listing shows both the usage of 'name' and 'tmp_name'.

Instead of readfile() you would let MySQL read it via the 'LOAD DATA LOCAL INFILE' query.

In case you first need to move the uploaded file, see move_uploaded_file() and furthermore read about it in the PHP manual section Handling File Uploads.


Caution: Never use the 'name' provided by the user, that is a security risk.

To give an example, in your code:

mysqli_query($connect,"LOAD DATA LOCAL INFILE $uploaded INTO TABLE table_name FIELDS TERMINATED BY ',' IGNORE 1 LINES; ");

the $uploaded variable contains arbitrary string data, the user can inject into the SQL query, changing it completely. See the warning about SQL Injection on mysqli_query() that shows how to prevent such injections.

Read Entire Article