我正在尝试编写一个脚本,将用户上传的CSV文件的内容保存到MySQL数据库中。我对将文件永久保存在服务器上不感兴趣——关键是允许用户通过批量上传在MySQL数据库中创建多个条目。
这是我迄今为止所拥有的。
HTML上传表单
<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>
将CSV文件的内容保存到MySQL数据库的PHP脚本
<?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>";
?>
我基本上只需要一些关于如何将两者联系起来的建议。我认为这将很容易命名PHP脚本BulkUploadStudents.PHP,为上传的文件名创建一个变量,然后用该变量替换"example.com/file.csv"。但不确定具体细节。
如有任何帮助,我们将不胜感激!
只需打开url后面的临时文件:
$file_handle = fopen($_FILES["uploadedfile"]['tmp_name'], "r");