2016-02-24 58 views
-1

我想在PHP上編寫一個代碼,它允許我將一些CSV文件的特定列上傳到MySql表格。我對PHP很新。試圖看一些教程,但他們沒有太大的幫助,因爲他們只顯示很少的CSV文件,如2行和2列的例子......我說的是大約100列和數百行。我只需要來自某些特定列的信息來添加我的表格。這是我的代碼,它給出了未定義的偏移錯誤。我接受新的想法。通過PHP將CSV文件上傳到MySql表格

$connection = mysqli_connect('localhost', 'root', 'MyPass', 'database') or die('connection failed'); 

if(isset($_POST['upload'])){ 

    $fname = $_FILES['sel_file']['name']; 
    echo 'upload file name: '.$fname.' '; 
    $chk_ext = explode(".",$fname); 

    if(strtolower(end($chk_ext)) == "csv") 
    { 

     $filename = $_FILES['sel_file']['tmp_name']; 
     $handle = fopen($filename, "r"); 

     while (($data = fgetcsv($handle, 10, ",")) !== FALSE) 
     { 
      $sql = "INSERT into turbolister(site,format,currency) values('$data[0]','$data[1]','$data[2]')"; 
      mysqli_query($connection, $sql) or die(mysqli_error($connection)); 
     } 

     fclose($handle); 
     echo "Successfully Imported"; 

    } 
    else 
    { 
     echo "Invalid File"; 
    }  


} ` 

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data"> 
 
      Import File: <input class="btn btn-primary" type="file" name='sel_file' size='20'> <br> 
 
      <input class="btn btn-primary" type="submit" name="upload" value='upload'> 
 
     </form>

+0

請顯示CSV文件以及 – Michael

回答

0

對於這樣的項目,我建議你這樣做的另一種方式。

對我來說有一些開放式的問題:

  • 它是正確的,在CSV一條線是在數據庫中的一個行?
  • csv中是否有包含列名的標題行,以便列的順序可以更改?

我已經過度修改了腳本 - 您需要做的是根據您的需要調整行爲,並更改標題欄和法線的分隔項。

<?php 

// Just for development purpose 
error_reporting(E_ALL); 
ini_set('display_errors', 1); 

try { 
    // Try to connect to mysql-server with pdo instated of using mysqli 
    $dbCon = new PDO('mysql:dbname=testdb;host=127.0.0.1', 'root', 'MyPass'); 
} catch (PDOException $e) { 
    // Catching error && stoping script 
    die('<strong>Error:</strong> Connection failed with error "' . $e->getMessage() . '"'); 
} 

if(isset($_POST['upload'])) { 
    $filename = $_FILES['sel_file']['name']; 

    // Show filename of uploaded file 
    echo 'Uploaded file: ' . $filename . '<br>'; 

    // Check file-extension for csv 
    // @ToDo: Determinate which mime-type your csv-files generally have and check for mime-type additionally or instated 
    if (pathinfo($filename, PATHINFO_EXTENSION) == 'csv') { 
     // Get file-content 
     $fileContent = file_get_contents($_FILES['sel_file']['tmp_name']); 

     // Split file into lines 
     $rows = explode("\n", $fileContent); 

     // Check for data 
     if (empty($rows) || count($rows) < 2) { 
      // Shwo error-messages && stopping script 
      die('<strong>Error:</strong> CSV-File does not contain data!'); 
     } 

     // Get columns of header-row 
     $header = explode('|', $rows[0]); 

     // Set query variables 
     $query = 'INSERT INTO test ('; 
     $values = '('; 

     // Build query based on header-columns 
     for($a = 0; $a < count($header); ++$a) { 
      // Add column 
      $query .= $header[$a] . ', '; 
      $values .= ':column' . $a . ', '; 
     } 

     // Finish query 
     $query = substr($query, 0, -2) . ') VALUES ' . substr($values, 0, -2) . ')'; 

     // Loop through rows, starting after header-row 
     for ($b = 1; $b < count($rows); ++$b) { 
      // Split row 
      $row = explode(',', $rows[$b]); 

      // Check that row has the same amount of columns like header 
      if (count($header) != count($row)) { 
       // Show message 
       echo '<strong>Warning:</strong> Skipped line #' . $b . ' because of missing columns!'; 

       // Skip line 
       continue; 
      } 

      // Create statement 
      $statement = $dbCon->prepare($query); 

      // Loop through columns 
      for ($c = 0; $c < count($row); ++$c) { 
       // Bind values from column to statement 
       $statement->bindValue(':column' . $c, $row[$c]); 
      } 

      // Execute statement 
      $result = $statement->execute(); 

      // Check for error 
      if ($result === false) { 
       // Show info 
       echo '<strong>Warning:</strong>: DB-Driver returned error on inserting line #' . $b; 
      } 
     } 

     // @ToDo: Get numbers of row before import, check number of rows after import against number of rows in file 
     // Show success message 
     echo '<span style="color: green; font-weight: bold;">Import successfully!</span>'; 
    } else { 
     die('<strong>Error:</strong> The file-extension of uploaded file is wrong! Needs to be ".csv".'); 
    } 
} 

?> 
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data"> 
    Import File: <input class="btn btn-primary" type="file" name='sel_file' size='20'> <br> 
    <input class="btn btn-primary" type="submit" name="upload" value='upload'> 
</form> 
+0

謝謝您的回答!這是非常聰明的做法。非常翔實的 和幫助! –

+0

我很高興能幫上忙。如果您將我的答案標記爲可接受的解決方案,那將會很好。 – SebTM