I am trying to write a script that will save the contents of a user-uploaded CSV file into a MySQL database. I am not interested in saving the file permanently on the server — the whole point is to just allow the user to create multiple entries in the MySQL database via a bulk upload.
Here’s what I have so far.
HTML upload form
<form enctype="multipart/form-data" action="BulkUploadStudents.php" method="POST">
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
PHP script that saves the contents of a CSV file into a MySQL database
<?php
$username="";
$password="";
$database="";
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$file_handle = fopen("http://www.example.com/file.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
$query = "INSERT INTO students VALUES ('','$line_of_text[0]','$line_of_text[1]','$line_of_text[2]')";
mysql_query($query);
}
fclose($file_handle);
echo "<p><b>Records succesfully imported</b></p>";
?>
I basically just need some advice on how to connect the two. I am thinking it would be as easy as naming that PHP script BulkUploadStudents.php, creating a variable for the uploaded file name, and then replacing the “example.com/file.csv” with the variable. Not sure about the specifics, though.
Any help would be greatly appreciated!
Just open the temporary file insted of the url: