简体   繁体   English

如何通过使用php导入excel文件在数据库表中插入值

[英]How to insert value in database table by importing excel file using php

my file upload code我的文件上传代码

<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Lumino - Dashboard</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/font-awesome.min.css" rel="stylesheet">
    <link href="css/datepicker3.css" rel="stylesheet">
    <link href="css/styles.css" rel="stylesheet">
    <link href="css/admin.css" rel="stylesheet">
    <!--Custom Font-->
    <link href="https://fonts.googleapis.com/css?family=Montserrat:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">
    <!--[if lt IE 9]>
      <script src="js/html5shiv.js"></script>
      <script src="js/respond.min.js"></script>
    <![endif]-->
    <style>
        .import {
            right: -430px !important;
            padding: 25px!important;
        }

        @media (max-width: 768px) {
            .import {
                right: 0px !important;
            }
            .navbar-fixed-bottom,
            .navbar-fixed-top {
                right: 86px!important;
                left: 0;
                z-index: 1030;
            }
        }
    </style>

</head>

<body>
    <?php include('dbc.php');?>
    <nav class="navbar navbar-custom navbar-fixed-top" role="navigation">
      <div class="container-fluid">
          <div class="navbar-header">
              <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#sidebar-collapse">
                  <span class="sr-only">Toggle navigation</span>
                  <span class="icon-bar"></span>
                  <span class="icon-bar"></span>
                  <span class="icon-bar"></span>
              </button>
              <a class="navbar-brand" href="#"> <span>Lumino</span>Admin</a>
              <ul class="nav navbar-top-links navbar-right">
                  <li class="dropdown">
                      <a class="dropdown-toggle count-info" data-toggle="dropdown" href="#">
                          <em class="fa fa-envelope"></em>
                      </a>
                      <ul class="dropdown-menu dropdown-messages">
                          <li>
                              <div class="dropdown-messages-box">
                                  <a href="profile.html" class="pull-left">
                                      <img alt="image" class="img-circle" src="http://placehold.it/40/30a5ff/fff">
                                  </a>
                                  <div class="message-body">
                                      <small class="pull-right">3 mins ago</small>
                                      <a href="#"><strong>John Doe</strong> commented on <strong>your photo</strong>.</a>
                                      <br/>
                                      <small class="text-muted">1:24 pm - 25/03/2015</small>
                                  </div>
                              </div>
                          </li>
                          <li class="divider"></li>
                          <li>
                              <div class="dropdown-messages-box">
                                  <a href="profile.html" class="pull-left">
                                      <img alt="image" class="img-circle" src="http://placehold.it/40/30a5ff/fff">
                                  </a>
                                  <div class="message-body">
                                      <small class="pull-right">1 hour ago</small>
                                      <a href="#">New message from <strong>Jane Doe</strong>.</a>
                                      <br/>
                                      <small class="text-muted">12:27 pm - 25/03/2015</small>
                                  </div>
                              </div>
                          </li>
                          <li class="divider"></li>
                          <li>
                              <div class="all-button">
                                  <a href="#"><em class="fa fa-inbox"></em> <strong>All Messages</strong></a>
                              </div>
                          </li>
                      </ul>
                  </li>
                  <li class="dropdown">
                      <a class="dropdown-toggle count-info" data-toggle="dropdown" href="#">
                          <em class="fa fa-bell"></em>
                      </a>
                      <ul class="dropdown-menu dropdown-alerts">
                          <li>
                              <a href="#">
                                  <div><em class="fa fa-envelope"></em> 1 New Message
                                      <span class="pull-right text-muted small">3 mins ago</span></div>
                              </a>
                          </li>
                          <li class="divider"></li>
                          <li>
                              <a href="#">
                                  <div>
                                    <em class="fa fa-heart"></em> 12 New Likes <span class="pull-right ext-muted small">4 mins ago</span>
                                  </div>
                              </a>
                          </li>
                          <li class="divider"></li>
                          <li>
                              <a href="#">
                                  <div>
                                    <em class="fa fa-user"></em> 5 New Followers <span class="pull-right text-muted  small">4 mins ago</span>
                                  </div>
                              </a>
                          </li>
                      </ul>
                  </li>
              </ul>
          </div>
      </div>
      <!-- /.container-fluid -->
    </nav>
    <div id="sidebar-collapse" class="col-sm-3 col-lg-2 sidebar">
        <div class="profile-sidebar">
            <div class="profile-userpic">
                <img src="http://placehold.it/50/30a5ff/fff" class="img-responsive" alt="">
            </div>
            <div class="profile-usertitle">
                <div class="profile-usertitle-name">Username</div>
                <div class="profile-usertitle-status"><span class="indicator label-success"></span>Online</div>
            </div>
            <div class="clear"></div>
        </div>
        <div class="divider"></div>
        <form role="search">
            <div class="form-group">
                <input type="text" class="form-control" placeholder="Search">
            </div>
        </form>
        <ul class="nav menu">
            <li class="active"><a href="index.html"><em class="fa fa-dashboard">&nbsp;</em> Dashboard</a></li>
            <li><a href="widgets.html"><em class="fa fa-calendar">&nbsp; </em> Widgets</a></li>
            <li><a href="charts.html"><em class="fa fa-bar-chart">&nbsp; </em> Charts</a></li>
            <li><a href="elements.html"><em class="fa fa-toggle-off">&nbsp; </em> UI Elements</a></li>
            <li><a href="panels.html"><em class="fa fa-clone">&nbsp;</em> Alerts &amp; Panels</a></li>
            <li class="parent ">
                <a data-toggle="collapse" href="#sub-item-1">
                    <em class="fa fa-navicon">&nbsp;</em> Multilevel 
                    <span data-toggle="collapse" href="#sub-item-1" class="icon pull-right"><em class="fa fa-plus"></em></span>
                </a>
                <ul class="children collapse" id="sub-item-1">
                    <li>
                        <a class="" href="#">
                            <span class="fa fa-arrow-right">&nbsp;</span> Sub Item 1
                        </a>
                    </li>
                    <li>
                        <a class="" href="#">
                            <span class="fa fa-arrow-right">&nbsp;</span> Sub Item 2
                        </a>
                    </li>
                    <li>
                        <a class="" href="#">
                            <span class="fa fa-arrow-right">&nbsp;</span> Sub Item 3
                        </a>
                    </li>
                </ul>
            </li>
            <li><a href="login.html"><em class="fa fa-power-off">&nbsp;</em> Logout</a></li>
        </ul>
    </div>
    <!--/.sidebar-->
    <div class="col-sm-9 col-sm-offset-3 col-lg-10 col-lg-offset-2 
     main">
        <div class="row">
            <ol class="breadcrumb">
                <li>
                    <a href="#">
                        <em class="fa fa-home"></em>
                    </a>
                </li>
                <li class="active">Dashboard</li>
            </ol>
        </div>
        <!--/.row-->
    </div>

    <div class="container">
        <form method="post" role="form" class="impfile">
            <h1 class="text-center">IMPORT FILE</h1>
            <p class="search_input col-sm-12  import">
                <input type="file" placeholder="From Date" id="file" name="file" required class="input-control" />
                <br>
                <input type="submit" name="import" value="import" id="import" class="btn btn-primary pull-center">
            </p>
        </form>
    </div>

    <?php error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE) ?>
      <?php
        if(isset($_POST["import"])) {
          ini_set('max_execution_time', 120); //300 seconds = 5 minutes
          //$filename = $_FILES['file']['name'];
          $file = $_FILES['file']['tmp_name'];
          //$ext=substr($file,strrpos($file,"."),(strlen($file)- 
          strrpos($file,".");
          //if($ext=="csv")
          $handle = fopen($file, "r");
          //$c = 0;
          while(($filesop = fgetcsv($handle,",")) !== false)
          {
            $category = mysqli_real_escape_string($conn,$filesop[0]);
            $tags = mysqli_real_escape_string($conn,$filesop[1]);
            $title = mysqli_real_escape_string($conn,$filesop[2]);
            $url =mysqli_real_escape_string($conn,$filesop[3]);
            $description = mysqli_real_escape_string($conn,$filesop[4]);
            $date = mysqli_real_escape_string($conn,$filesop[5]);
            //print_r($filesop[0]);
            var_dump($filesop);
            //echo $filesop[0];
            $sql = "insert into report(category,tags,title,url,description,date) values ('$category','$tags','$title','$url','$description','$date')";
            //$c = $c + 1;
            $result=mysqli_query($conn,$sql)or die($sql."<br/><br/>".mysql_error());
            //echo $sql;
            //echo $filesop[1];
            //echo "success";
            exit();
          }
          //if($result){
            //echo " upload success";
            //ini_set('auto_detect_line_endings',FALSE);
            fclose($handle);
          // }
          //else
          // echo "cannot upload csv file";
        }
      mysqli_close($conn);        
    ?>
    <!--/.main-->
    <script src="js/jquery-1.11.1.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/chart.min.js"></script>
    <script src="js/chart-data.js"></script>
    <script src="js/easypiechart.js"></script>
    <script src="js/easypiechart-data.js"></script>
    <script src="js/bootstrap-datepicker.js"></script>
    <script src="js/custom.js"></script>
    <script>
        window.onload = function() {
                var chart1 = document.getElementById("line- 
                    chart ").getContext("
                    2 d ");
                    window.myLine = new Chart(chart1).Line(lineChartData, {
                        responsive: true,
                        scaleLineColor: "rgba(0,0,0,.2)",
                        scaleGridLineColor: "rgba(0,0,0,.05)",
                        scaleFontColor: "#c5c7cc"
                    });
                };
    </script>
</body>
</html>

Below is my csv file data.以下是我的 csv 文件数据。

Marketing & Customer Analytics,Trends & Product Updates,Segment Launches Segment Select, https://martechseries.com/analytics/customer-data-platforms/segment-launches-segment-select-new-program-help-companies-leverage-first-party-data-certified-partners/ ,"Segment, the customer data infrastructure company, launched Segment Select, a new program designed to help Channel and Technology Partners easily build and implement solutions for their customers that leverage Segment's Customer Data Infrastructure (CDI).",2/24/2019营销和客户分析,趋势和产品更新,细分市场推出细分市场, https://martechseries.com/analytics/customer-data-platforms/segment-launches-segment-select-new-program-help-companies-leverage-first -party-data-certified-partners/ ,“客户数据基础设施公司 Segment 推出了 Segment Select,这是一项新计划,旨在帮助渠道和技术合作伙伴利用 Segment 的客户数据基础设施 (CDI) 轻松为其客户构建和实施解决方案.",2/24/2019

My database table screenshort我的数据库表屏幕截图在此处输入图片说明

You have missed form attribute enctype .您错过了表单属性enctype

You need to update in form attribute enctype in the form tag.您需要更新表单标签中的表单属性enctype

Your current syntax is:- <form method="post" role="form" class="impfile">您当前的语法是:- <form method="post" role="form" class="impfile">

Need to update with :- <form method="post" role="form" class="impfile" enctype="multipart/form-data">需要更新:- <form method="post" role="form" class="impfile" enctype="multipart/form-data">

Please check below code:请检查以下代码:

<form method="post" role="form" class="impfile" enctype="multipart/form-data">
    <h1 class="text-center">IMPORT FILE</h1>
    <p class="search_input col-sm-12  import">
        <input type="file" placeholder="From Date" id="file" name="file" required class="input-control" />
        <br>
        <input type="submit" name="import" value="import" id="import" class="btn btn-primary pull-center">
    </p>
</form>

Updated更新

Update for If CSV file contains 2 or more rows.更新如果 CSV 文件包含 2 行或更多行。 Please check below code请检查以下代码

while (($row = fgetcsv($handle, ",")) !== false) 
{ 
  if (empty($fields)){
    $fields = $row;
    continue;
  }         
  foreach ($row as $k=>$value) 
  {   
    $results[$col][$k] = $value;
  }
  $col++;
  unset($row);
}
if (!feof($handle)) 
{
  echo "Error: unexpected fgets() failn";
}
fclose($handle);

foreach ($results as $key => $value) {
  $category = mysqli_real_escape_string($conn,$value[0]);
  $tags = mysqli_real_escape_string($conn,$value[1]);
  $title = mysqli_real_escape_string($conn,$value[2]);
  $url =mysqli_real_escape_string($conn,$value[3]);
  $description = mysqli_real_escape_string($conn,$value[4]);
  $date = mysqli_real_escape_string($conn,$value[5]);
  $sql = "insert into report(category,tags,title,url,description,date) values ('$category','$tags','$title','$url','$description','$date')";
  $result=mysqli_query($conn,$sql)or die($sql."<br/><br/>".mysqli_error());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM