2012-08-09 88 views
3

我知道還有其他類似的帖子,但是大家都推薦直接在PHPMyAdmin中將其轉換爲MySQL(這很好用,但我需要導入通過一個HTML表格到PHP到MySQL使用PHP代碼和HTML格式將excel(.csv)導入到MySQL中

我想要一個HTML表單來收集文件,然後將該文件傳遞給PHP腳本,我想知道是否可以簡單地調用PHP函數該轉換逗號delimeted .csv文件到MySQL並將其添加到數據庫中。

或者是解析由行的文件行並添加每個記錄的唯一途徑?

+0

PHPMyAdmin使用HTML表單和PHP。閱讀其來源,看看他們是如何做到的。 – 2012-08-09 23:44:21

+0

查看http://code.google.com/p/php-csv-parser/它會將.csv轉換爲數組。然後,您可以循環訪問數組並構建INSERT查詢。 – JDavis 2012-08-10 00:05:28

回答

7

我還沒有完全測試過這個,但我看不出有什麼理由不起作用。

<?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> 

當然,您需要先驗證數據。

+0

+1這是非常有用的:) – 2012-08-27 01:04:53

+0

進行得很好,只需要爲其他數據庫稍微修改一下。你能告訴我如何導出?我將非常感激。 – Kasnady 2013-12-30 06:59:53

1

我們之前使用過它,它工作得很好。只要看你的文件和目錄權限。 csv_upload_mysql_conf.inc就是數據庫鏈接。這將一次解析多個文件,並將它們放入一個名爲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; 
} 

?> 
+0

90%不是我的代碼,也不是這樣聲稱。使用它需要您自擔風險......這一切都在谷歌搜索結果。我相信可以做出一些改進。另外,請原諒我們的懶惰文件擴展名數組。我們有時會允許txt文件,所以我們只用一個值來保留數組代碼。 – 2012-08-10 02:27:16

1

您的代碼中的所有內容都很好,唯一的錯誤是您沒有使用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> 
+0

我不想實際將數據放入數據庫中,因爲沒有必要回答他的問題。我只是想展示一個可以運行和測試的工作示例,以查看查詢的外觀。我很確定你的例子會失敗,如果你試圖運行它。理想情況下,您可以使用'PDO'和'bindParam',而不是連接一系列'INSERT INTO'語句。 – JDavis 2013-03-12 19:28:56