使用PHP将CSV转换为MySQL
我正在尝试使用php将students.csv文件中的数据导入mysql。csv文件中的条目以某种方式将列(学生编号、fname、lname、level)插入到biodata表中 我还在从我的电脑上传student.csv文件 当我运行页面时,屏幕上没有显示任何内容使用PHP将CSV转换为MySQL,php,mysql,csv,Php,Mysql,Csv,我正在尝试使用php将students.csv文件中的数据导入mysql。csv文件中的条目以某种方式将列(学生编号、fname、lname、level)插入到biodata表中 我还在从我的电脑上传student.csv文件 当我运行页面时,屏幕上没有显示任何内容 session_start(); require('includes/dbconnect.php'); require 'includes/header.inc.php'; //check for file upload if (
session_start();
require('includes/dbconnect.php');
require 'includes/header.inc.php';
//check for file upload
if (isset($_FILES['csv_file']) && is_uploaded_file($_FILES['csv_file']['tmp_name'])) {
//upload directory
$upload_dir = "C:\Users\DOTMAN\Documents\students.csv";
//create file name
$file_path = $upload_dir . $_FILES['csv_file']['name'];
//move uploaded file to upload dir
if (!move_uploaded_file($_FILES['csv_file']['tmp_name'], $file_path)) {
//error moving upload file
echo "Error moving file upload";
}
//open the csv file for reading
$handle = fopen($file_path, 'r');
//turn off autocommit and deletethe bio data
mysql_query("SET AUTOCOMMIT=0");
mysql_query("BEGIN");
mysql_query("TRUNCATE TABLE biodata") or die(mysql_error());
while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
//Access field data in $data array ex.
$student_number = $data[0];
$fname = $data[1];
$lname = $data[2];
$level = $data[3];
//Use data to insert into db
$query = "INSERT INTO biodata (student_number, fname, lname, level)
VALUES ('$student_number', '$fname', '$lname', '$level')";
mysql_query($query) or die (mysql_error());
}
}
我建议您使用命令上传CSV文件。这是一个快速的方法。 如果你只需要做一次,我会考虑使用类似的东西: 我能看到的一个即时问题在这里:
$upload_dir = "C:\Users\DOTMAN\Documents\students.csv";
//create file name
$file_path = $upload_dir . $_FILES['csv_file']['name'];
您已经将整个路径(包括文件名)分配给$upload\u dir
变量,然后再次追加上载的文件名
如果您认为代码中存在错误,请从添加
ini_set('display_errors', 1);
error_reporting(E_ALL);
添加到PHP代码的开头,并修复显示的任何警告/错误。然后,您可以通过在第一次调用中将第二个参数更改为0来关闭打印错误消息。让您调试$\u文件:
print_r($_FILES);
在做任何事情之前使用PHP解决方案
$file='path/to.csv';
$lines=文件($file);
$firstLine=$lines[0];
foreach($line作为$line_num=>$line的行){
如果($line_num==0){continue;}//转义标题列
$arr=分解(“,”,$line);
$column1=$arr[0];
$column2=$arr[1];
回声$column1.$column2.“
”;
//将mysql insert语句放在这里
}
是因为它运行时没有错误吗?。。尝试添加一些'echo'语句,看看发生了什么服务器日志中有错误吗?服务器日志中没有错误。在不尝试格式化的情况下发布这样的代码表明您对comunity的不尊重。您是否尝试将php设置为显示错误并报告错误(E_ALL&~E_注意);ini设置(“显示错误”,1);ini设置(“显示启动错误”,1);ini_集('output_buffering',0)代码>是的,这是可能的,但我计划很快向公众部署。谢谢你上传了这个文件。我得到了Name、Type、Temp Name、error和size的值。但是里面的数据值仍然没有插入到数据库中。请帮助我。现在检查您的$file\u路径,文件已正确上载。您还必须进行调试。
$file = 'path/to.csv';
$lines = file($file);
$firstLine = $lines[0];
foreach ($lines as $line_num => $line) {
if($line_num==0) { continue; } //escape the header column
$arr = explode(",",$line);
$column1= $arr[0];
$column2= $arr[1];
echo $column1.$column2."<br />";
//put the mysql insert statement here
}