PHP script to import csv data into mysql

前端 未结 4 573
囚心锁ツ
囚心锁ツ 2020-12-23 11:03

I have tried the following code but getting some errors. Here I can read the input file but I am getting the following error:Deprecated: Function split() is deprecated in C:

相关标签:
4条回答
  • 2020-12-23 11:08

    Try this:

    <?php
    // specify connection info
    $connect = mysql_connect('localhost','root','12345');
    if (!$connect)
    {
       die('Could not <span id="IL_AD1" class="IL_AD">
        connect to</span> MySQL: ' . mysql_error());
    }
    
    $cid =mysql_select_db('test',$connect); //specify db name
    
    define('CSV_PATH','C:/wamp/www/csvfile/'); // specify CSV file path
    
    $csv_file = CSV_PATH . "infotuts.csv"; // Name of your CSV file
    $csvfile = fopen($csv_file, 'r');
    $theData = fgets($csvfile);
    $i = 0;
    while (!feof($csvfile))
    {
       $csv_data[] = fgets($csvfile, 1024);
       $csv_array = explode(",", $csv_data[$i]);
       $insert_csv = array();
       $insert_csv['ID'] = $csv_array[0];
       $insert_csv['name'] = $csv_array[1];
       $insert_csv['email'] = $csv_array[2];
       $query = "INSERT INTO csvdata(ID,name,email)
         VALUES('','".$insert_csv['name']."','".$insert_csv['email']."')";
       $n=mysql_query($query, $connect );
       $i++;
    }
    fclose($csvfile);
    echo "File data successfully imported to database!!";
    mysql_close($connect); // closing connection
    ?>
    
    0 讨论(0)
  • 2020-12-23 11:16

    Several tips:

    • Don't use the deprecated ext/mysql, when you can use ext/mysqli or PDO.

    • Don't read the entire csv file into a PHP variable. What happens when the file is 500MB?

    • Don't write custom PHP code to parse csv data, when you can use the builtin function fgetcsv().

    • Don't create a new SQL statement for every row in the data, when you can use prepared statements.

    • Don't interpolate data from an external file into SQL statements. This risks SQL injection vulnerabilities, just like when you interpolate untrusted user input.

    • Don't parse and insert csv data row by row, when you can use MySQL's LOAD DATA INFILE command. It's 20x faster than inserting row by row.

    Here's a simpler solution:

    <?php
    $databasehost = "localhost"; 
    $databasename = "test"; 
    $databasetable = "sample"; 
    $databaseusername="test"; 
    $databasepassword = ""; 
    $fieldseparator = ","; 
    $lineseparator = "\n";
    $csvfile = "filename.csv";
    
    if(!file_exists($csvfile)) {
        die("File not found. Make sure you specified the correct path.");
    }
    
    try {
        $pdo = new PDO("mysql:host=$databasehost;dbname=$databasename", 
            $databaseusername, $databasepassword,
            array(
                PDO::MYSQL_ATTR_LOCAL_INFILE => true,
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
            )
        );
    } catch (PDOException $e) {
        die("database connection failed: ".$e->getMessage());
    }
    
    $affectedRows = $pdo->exec("
        LOAD DATA LOCAL INFILE ".$pdo->quote($csvfile)." INTO TABLE `$databasetable`
          FIELDS TERMINATED BY ".$pdo->quote($fieldseparator)."
          LINES TERMINATED BY ".$pdo->quote($lineseparator));
    
    echo "Loaded a total of $affectedRows records from this csv file.\n";
    
    ?>
    

    I tested this with PHP 5.3.26 on a Mac, connecting to MySQL 5.6.14 on Linux.

    0 讨论(0)
  • 2020-12-23 11:19
    **Data Import And Export**
    **CSV To Mysql AND Mysql To CSV Using Mysqli**    
    <!DOCTYPE html>
        <!--
        To change this license header, choose License Headers in Project Properties.
        To change this template file, choose Tools | Templates
        and open the template in the editor.
        -->
        <html>
            <head>
                <meta charset="UTF-8">
                <title></title>
            </head>
            <body>
                <form method="post">
                    <button type="submit" name="btn_export">Data Export</button>
                    <button type="submit" name="btn_import">Data Import</button>
                </form>
                <?php
                $host = "localhost";
                $uname = "root";
                $pass = "";
                $database = "demo"; //Change Your Database Name
                $conn = new mysqli($host, $uname, $pass, $database)or die("No Connection");
                echo mysql_error();
        //MYSQL MYADDMINPHP TO CSV
                if (isset($_REQUEST['btn_export']))
                {
                    $data_op = "";
                    $sql = $conn->query("select * from users"); //Change Your Table Name          
                    while ($row1 = $sql->fetch_field())
                    {
                        $data_op .= '"' . $row1->name . '",';
                    }
                    $data_op .="\n";
                    while ($row = $sql->fetch_assoc())
                    {
                        foreach ($row as $key => $value)
                        {
                            $data_op .='"' . $value . '",';
                        }
                        $data_op .="\n";
                    }
                    $filename = "Database.csv"; //Change File type CSV/TXT etc
                    header('Content-type: application/csv'); //Change File type CSV/TXT etc
                    header('Content-Disposition: attachment; filename=' . $filename);
                    echo $data_op;
                    exit;
                }
        //CSV To MYSQL MYADDMINPHP
                if (isset($_REQUEST['btn_import']))
                {
                    $filename = 'Database.csv';
                    $fp = fopen($filename, "r");
                    while (($row = fgetcsv($fp, "40", ",")) != FALSE)
                    {
                        $sql = "INSERT INTO users (name,pass,city,id) VALUES('" . implode("','", $row) . "')";
                        if (!$conn->query($sql))
                        {
                            echo '<br>Data No Insert<br>';
                        }
                    }
                    fclose($fp);
                }
                ?>
            </body>
        </html>
    
    0 讨论(0)
  • 2020-12-23 11:31

    I think you need to convert CSV file in collection first. After that you can add loop and call insert queries to insert data.

    Here you will get code to convert CSV file into collection array. best-way-to-upload-and-read-csv-file-in-php

    0 讨论(0)
提交回复
热议问题