Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/234.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用PHP将CSV文件上传到MySql表_Php_Mysql_Database_Csv - Fatal编程技术网

用PHP将CSV文件上传到MySql表

用PHP将CSV文件上传到MySql表,php,mysql,database,csv,Php,Mysql,Database,Csv,我试图在PHP上编写一个代码,允许我将一些特定列从CSV文件上传到MySql表。我对PHP非常陌生。尝试观看一些教程,但没有多大帮助,因为它们只在非常小的CSV文件(如2行和2列)上显示示例。。。我所说的是大约100列和数百列。我只需要一些特定列的信息来添加我的表。这是我到目前为止的代码。。它给出了未定义的偏移误差。我乐于接受新思想 $connection = mysqli_connect('localhost', 'root', 'MyPass', 'database') or die('co

我试图在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";
     }     


} `

对于这样一个项目,我会向您推荐另一种方法

对我来说,有一些悬而未决的问题:

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


请同时显示CSV文件谢谢您的回答!这真是一个聪明的方法。信息量大,很有帮助!