使用PHP代码和HTML表单将excel(.csv)导入MySQL

我知道还有其他类似的post,但是所有人都build议直接在PHPMyAdmin中将其转换为MySQL(这是完美的,但是我需要通过HTML表单将数据导入到PHP中)。

我想有一个收集文件的HTML表单。 然后将该文件传递给PHP脚本,我想知道是否可以简单地调用一个PHP函数,将逗号分隔的.csv文件转换为MySQL并将其添加到数据库中。

或者是逐行parsing文件并添加每条logging的唯一方法?

我还没有完全testing这个,但我没有看到任何理由不起作用。

<?php if ( isset( $_FILES['userfile'] ) ) { $csv_file = $_FILES['userfile']['tmp_name']; if ( ! is_file( $csv_file ) ) exit('File not found.'); $sql = ''; if (($handle = fopen( $csv_file, "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $sql .= "INSERT INTO `table` SET `column0` = '$data[0]', `column1` = '$data[1]', `column2` = '$data[2]'; "; } fclose($handle); } // Insert into database //exit( $sql ); exit( "Complete!" ); } ?> <!DOCTYPE html> <html> <head> <title>CSV to MySQL Via PHP</title> </head> <body> <form enctype="multipart/form-data" method="POST"> <input name="userfile" type="file"> <input type="submit" value="Upload"> </form> </body> </html> 

当然,你需要首先validation数据。

我们之前使用过,而且工作得很好。 只要看你的文件和目录权限。 csv_upload_mysql_conf.inc就是数据库链接。 这将一次parsing多个文件,并将其放在一个名为import的表中。 相应地更新。

 <?php /* The conf file */ include_once "csv_upload_mysql_conf.inc"; $php_self = $_SERVER['PHP_SELF']; $file_open = 0; $file_exts = array ( 'csv'); #Our Form..... $form = <<< EOFFORM <div align='center' style='border: 1px solid #CCC; background-color: #FAFAFA;padding: 10px; color: #006699; width: 620px; font-family: palatino, verdana, arial, sans-serif;' > <table align=center style='border: 1px solid #CCC; background-color: #FFF;padding: 20px; color: #006699;' cellspacing=1><tbody> <tr><td> <form enctype='multipart/form-data' action='$php_self' method='post'><input type='hidden' name='MAX_FILE_SIZE' value='2000000' /><input type='hidden' name='selected' value='yes' /> Selected file: <input name='userfile[]' type='file' id='userfile[]' multiple='' onChange='makeFileList();' /><br /><br /><input type='submit' value='Upload CSV' /> </td></tr></tbody></table></div> <p> <strong>Files You Selected:</strong> </p> <ul id="fileList"><li>No Files Selected</li></ul> <script type='text/javascript'> function makeFileList() { var input = document.getElementById('userfile[]'); var ul = document.getElementById('fileList'); while (ul.hasChildNodes()) { ul.removeChild(ul.firstChild); } for (var i = 0; i < input.files.length; i++) { var li = document.createElement('li'); li.innerHTML = input.files[i].name; ul.appendChild(li); } if(!ul.hasChildNodes()) { var li = document.createElement('li'); li.innerHTML = 'No Files Selected'; ul.appendChild(li); } } </script> EOFFORM; #End Form; if(!isset($_POST['selected'])){ echo "$form"; } elseif($_POST['selected'] == "yes"){ $uploaddir = 'uploads/'; if(count($_FILES['userfile']['name'])) { foreach ($_FILES['userfile']['name'] as $key => $error) { if ($error == UPLOAD_ERR_OK) { $tmp_name = $_FILES['userfile']['tmp_name'][$key]; $name = $_FILES['userfile']['name'][$key]; $f_type = trim(strtolower(end(explode('.', $name)))); if (!in_array($f_type, $file_exts)) die("Sorry, $f_type files not allowed"); } $uploadfile = $uploaddir . $name; if (! file_exists($uploadfile)) { if (move_uploaded_file($tmp_name, $uploadfile)) { print "File is valid, and was successfully uploaded. "; $flag = 1; chmod($uploadfile, 0777); } else { print "File Upload Failed. "; $flag = 0; } $flag = 1; if ($flag == 1) { echo "\n parsing Data..."; flush(); if (file_exists($uploadfile)) { $fp = fopen($uploadfile, 'r') or die (" Can't open the file"); $fileopen = 1; $length = calculate_length($uploadfile); } $replace = "REPLACE"; $field_terminater = ","; $enclose_option = 1; $enclosed = '"'; $escaped = '\\\\'; $line_terminator = 1; $local_option = 1; $sql_query = 'LOAD DATA'; if ($local_option == "1") { $sql_query .= ' LOCAL'; } $sql_query .= ' INFILE \'' . $uploadfile . '\''; if (!empty($replace)) { $sql_query .= ' ' . $replace; } $sql_query .= ' INTO TABLE ' . "`import`"; if (isset($field_terminater)) { $sql_query .= ' FIELDS TERMINATED BY \'' . $field_terminater . '\''; } if (isset($enclose_option) && strlen($enclose_option) > 0) { $sql_query .= ' OPTIONALLY'; } if (strlen($enclosed) > 0) { $sql_query .= ' ENCLOSED BY \'' . $enclosed . '\''; } if (strlen($escaped) > 0) { $sql_query .= ' ESCAPED BY \'' . $escaped . '\''; } if (strlen($line_terminator) > 0){ $sql_query .= ' LINES TERMINATED BY \'' . '\r\n' . '\''; } $result = mysql_query ($sql_query); echo mysql_error() ; if(mysql_affected_rows() > 1) { echo " <div align=center><b><font color=#66CC33>The csv data was added.</font></div> "; } else { error_log(mysql_error()); echo " <div align=center><b><font color=#E96B10> Couldn't enter the data to db </font></div>"; } if ($file_open ==1) { fclose($fp) or die("Couldn't close the file"); } } } } echo "<meta http-equiv='refresh' content='0; url=index.php'>"; } } function calculate_length($fp) { $length = 1000; $array = file($fp); for($i=0;$i<count($array);$i++) { if ($length < strlen($array[$i])) { $length = strlen($array[$i]); } } unset($array); return $length; } ?> 

你的代码中的一切都很好,唯一的错误是你没有使用mysql_query将数据插入到表中。 Mysql查询不在脚本中运行。 更正的代码如下…

  <?php if ( isset( $_FILES['userfile'] ) ) { $csv_file = $_FILES['userfile']['tmp_name']; if ( ! is_file( $csv_file ) ) exit('File not found.'); $sql = ''; if (($handle = fopen( $csv_file, "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $sql = mysql_query("INSERT INTO `table` SET `column0` = '$data[0]', `column1` = '$data[1]', `column2` = '$data[2]'; "); } fclose($handle); } // Insert into database //exit( $sql ); exit( "Complete!" ); } ?> <!DOCTYPE html> <html> <head> <title>CSV to MySQL Via PHP</title> </head> <body> <form enctype="multipart/form-data" method="POST"> <input name="userfile" type="file"> <input type="submit" value="Upload"> </form> </body> </html>