通过PHP将CSV文件上传到MySql表

时间:2016-02-24 14:07:42

标签: php mysql database csv

我正在尝试在PHP上编写一个代码,允许我将一些特定的列从CSV文件上传到MySql表。我是PHP的新手。试图观看一些教程,但它们没什么用,因为它们只显示非常小的CSV文件的示例,例如2行和2列......我说的是大约100列和数百行。我只需要来自某些特定列的信息来添加我的表。这是我的代码到目前为止..它给出了未定义的偏移误差。我对新想法持开放态度。

$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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分: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>