使用php将csv文件导入数据库

时间:2016-02-28 15:37:34

标签: php mysql csv import

我创建了以下php代码,将.csv文件导入到phpmyadmin上运行的mysql数据库中。代码如下:

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = '';

$database = 'mydatabase';
$table = 'demo';

if (!@mysql_connect($db_host, $db_user, $db_pwd))
    die("Can't connect to database");

if (!mysql_select_db($database))
    die("Can't select database");


    if(isset($_POST['submit']))
    {
         $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, 1000, ",")) !== FALSE)
             {
                $sql = "INSERT into demo(orders,quantity,country,dates,comment) values('$data[0]','$data[1]','$data[2]', '$data[3]','$data[4]')";
                mysql_query($sql) or die(mysql_error());
             }

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

         }
         else
         {
             echo "Invalid File";
         }   
    }

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

提交.csv文件后,会显示消息&#34;已成功导入&#34;但是当我检查数据库时,只会将.csv文件中的第一行导入数据库。其他记录不是。

1 个答案:

答案 0 :(得分:0)

唐使用mysql_将其更改为PDO或mysqli。话虽如此,我已经更改了您的代码以爆炸每一行,然后将值分配给列表。它对我有用。

if(isset($_POST['submit']))
{
    $fname = $_FILES['sel_file']['name'];
    echo 'upload file name: '.$fname.' ';

    $chk_ext = explode(".",$fname);

    if(strtolower(end($chk_ext)) == "csv")
    {
        foreach (file($fname) as $row)
        {
            list($data0, $data1, $data2, $data3, $data4) = explode(",", $row);
            $sql = "INSERT into demo(orders,quantity,country,dates,comment) values('$data0','$data1','$data2', '$data3','$data4')";
            mysql_query($sql) or die(mysql_error());
        }

        echo "Successfully Imported";
    }
    else
    {
        echo "Invalid File";
    }   
}