如何使用PHP将数据从csv文件保存到数据库

时间:2014-04-01 10:32:01

标签: php mysql csv

我想将csv文件保存到数据库中 这是我的代码:

<title>Upload page</title>
<style type="text/css">
body {
                background: #E3F4FC;
                font: normal 14px/30px Helvetica, Arial, sans-serif;
                    color: #2b2b2b;
                }
            a {
                color:#898989;
                font-size:14px;
                font-weight:bold;
                text-decoration:none;
            }
            a:hover {
                color:#CC0033;
            }

            h1 {
                font: bold 14px Helvetica, Arial, sans-serif;
                color: #CC0033;
            }
            h2 {
                font: bold 14px Helvetica, Arial, sans-serif;
                color: #898989;
            }
            #container {
                background: #CCC;
                margin: 100px auto;
                width: 945px;
            }
            #form           {padding: 20px 150px;}
            #form input     {margin-bottom: 20px;}
            </style>
            </head>
            <body>
            <div id="container">
            <div id="form">

            <?php

            include "e2.php"; //Connect to Database

            $deleterecords = "TRUNCATE TABLE books"; //empty the table of its current records
            mysql_query($deleterecords);

            //Upload File
            if (isset($_POST['submit'])) {
                if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
                echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
                    echo "<h2>Displaying contents:</h2>";
                    readfile($_FILES['filename']['tmp_name']);
                }

                //Import uploaded file to Database
                $handle = fopen($_FILES['filename']['tmp_name'], "r");

                while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                    $import="INSERT INTO books (BookID,Title,Author,PublisherName,CopyrightYear) VALUES('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]')";

                    mysql_query($import) or die(mysql_error());
                }

                fclose($handle);

                print "Import done";

                //view upload form
            }else {

                print "Upload new csv by browsing to file and clicking on Upload<br />\n";

                print "<form enctype='multipart/form-data' action='index.php' method='post'>";

                print "File name to import:<br />\n";

                print "<input size='50' type='file' name='filename'><br />\n";

                print "<input type='submit' name='submit' value='Upload'></form>";

            }

            ?>

            </div>
            </div>
            </body>
            </html>

这是e2.php文件:

$db = mysql_connect("localhost","root","") or die("Could not connect.");

if(!$db)

    die("no db");

if(!mysql_select_db("books",$db))

    die("No database selected.");

问题是如何同时在两个表中保存数据,在csv文件中有给每个单元格的链接,例如:A1是到sheet2的超链接,我想保存第2页数据,就像A1是主键一样。

这里是book.csv sheet1保存在&#34; books&#34;表

1   Geography Namrata Harshal 01-04-14
2   Geography Namrata Harshal 02-04-14
3   Geography Namrata Harshal 03-04-14
4   Geography Namrata Harshal 04-04-14
5   Geography Namrata Harshal 05-04-14
6   Hindi   Namrata Harshal 06-04-14
7   Hindi   Namrata Harshal 07-04-14
8   Hindi   Namrata Harshal 08-04-14
9   Hindi   Namrata Harshal 09-04-14
10  Hindi   Namrata Harshal 10-04-14

这里是book.csv sheet2保存在&#34;详细信息&#34;表

Geography   Namrata Harshal 02-04-14
Geography   Namrata Harshal 03-04-14
Geography   Namrata Harshal 04-04-14
Geography   Namrata Harshal 05-04-14

2 个答案:

答案 0 :(得分:4)

使用fgetcsv功能从CSV文件中获取数据。

$row = 1;
if (($openfile = fopen("customer.csv", "r")) !== FALSE) {
   while ($getdata = fgetcsv($openfile, 1000, ",")) {
       $total = count($getdata);
       echo "<b>Row no:-</b>$row\n";   
       echo "<b>Total fields in this row:-</b>$total\n";
       $row++;
       for ($c=0; $c < $total; $c++) {
          $csvdata = implode(";", $getdata);
          $fncsvdata = explode(";", $csvdata);
       }
       var_dump($fncsvdata);
   }
}

在这里,您可以看到CSV文件数据,而不是要使用INSERT查询插入数据 对于插入frist colum,请使用$fncsvdata[0] 这里fgetcsv 1000 =&#34;必须大于CSV文件中的最长行(以字符为单位)&#34;。

答案 1 :(得分:1)

我想建议这段代码 -

<?php 
$tmpfile=books.csv;
$csv=fopen($tmpfile,"r");
$i=0; 
while(!feof($csv))
{
   $data=fgetcsv($csv);
   if($i>=1)
   {
      $catagory=addslashes($data[0]);
      if($i==0||$data[0]=='')
      {
         // Here Your Insert Code
      }
   }
   $i++;
}
fclose($csv);
?>