【问题标题】:import csv in mysql db using ajax and php使用ajax和php在mysql db中导入csv
【发布时间】:2019-03-18 23:09:04
【问题描述】:

我正在做一个通过 ajax 将 csv 文件导入数据库的迷你项目,它工作正常。

这是我的文件

<?php
// creating database connection , executing queries and storing results
$connect = mysqli_connect("localhost","root", "", "dbname" );
$query = "SELECT * FROM csv ORDER BY id desc ";
$result = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Marks Statistics</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
       <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
       <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> 
</script>
</head>
<body>
<br/><br/>
<div class="container", style="width: 1000px;">
<h3 align="center">CSV DATABASE</h3><br/>
<!-- creating upload form -->

<form id="upload_csv" method="post" enctype="multipart/form-data">
      <div class="col-md-3">
        <label>Upload More Files</label>
    </div>
    <div class="col-md-4">
        <input type="file" name="marks_file" />
    </div>
    <div class="col-md-5" >
        <input type="submit" name="upload" id="upload" value="upload"  class="btn btn-info">
    </div>
    <div style= "clear:both"></div>
</form>
<br/><br/><br/>
    <!-- HTML table to display contents of the csv file -->
   <div class="table-responsive" id="marks_table">
    <table class="table table-bordered">
        <tr>
            <th width="25%" >name</th>
            <th width="15%" >Physics</th>
            <th width="15%" >Maths</th>
            <th width="15%" >Chemistry</th>
            <th width="15%" >Biology</th>
            <th width="15%" >SST</th>
        </tr>
        <?php
        while ($row = mysqli_fetch_array($result))
        {

        ?>
        <!-- append row data into table -->
        <tr>
            <td><?php echo $row["name"]; ?> </td>
            <td><?php echo $row["Physics"]; ?> </td>
            <td><?php echo $row["Maths"]; ?> </td>
            <td><?php echo $row["Chemistry"]; ?> </td>
            <td><?php echo $row["Biology"]; ?> </td>
            <td><?php echo $row["SST"]; ?> </td>
       <?php
        }
        ?>
</table>
</div>
</div>
</body>
</html>
<script>
  $(document).ready(function(){
       $('#upload_csv').on("submit", function(e){
            e.preventDefault(); //form will not submitted
            $.ajax({
                 url:"export.php",
                 method:"POST",
                 data:new FormData(this),
                 contentType:false,          // The content type used when sending data to the server.
                 cache:false,                // To unable request pages to be cached
                 processData:false,          // To send DOMDocument or non processed data file it is set to false
                 success: function(data){
                      if(data=='errorx')
                      {
                           alert("Invalid File");
                      }
                      else if(data == "errory")
                      {
                           alert("Please Select File");
                      }
                      else
                      {
                           $('#marks_table').html(data);
                      }
                 }
            })
       });  
  });
 </script>

 //export.php
<?php
if(!empty($_FILES["marks_file"]["name"]))
{
  $connect = mysqli_connect("localhost", "root", "", "dbname");
  $output = '';
  $allowed_ext = array("csv");
  $extension = end(explode(".", $_FILES["marks_file"]["name"]));
  if(in_array($extension, $allowed_ext))
  {
       $file_data = fopen($_FILES["marks_file"]["tmp_name"], 'r');
       fgetcsv($file_data);
       while($row = fgetcsv($file_data))
       {
            $name = mysqli_real_escape_string($connect, $row[0]);
            $Physics = mysqli_real_escape_string($connect, $row[1]);
            $Maths = mysqli_real_escape_string($connect, $row[2]);
            $Chemistry = mysqli_real_escape_string($connect, $row[3]);
            $Biology = mysqli_real_escape_string($connect, $row[4]);
            $SST = mysqli_real_escape_string($connect, $row[5]);
            $query = "
            INSERT INTO csv
                 (name, Physics, Maths, Chemistry, Biology, SST)
                 VALUES ('$name', '$Physics', '$Maths', '$Chemistry', '$Biology' , '$SST')
            ";
            mysqli_query($connect, $query);
       }
       $select = "SELECT * FROM csv ORDER BY id DESC";
       $result = mysqli_query($connect, $select);
       $output .= '
       <table class="table table-bordered">
           <tr>
               <th width="25%" >name</th>
               <th width="15%" >Physics</th>
               <th width="15%" >Maths</th>
               <th width="15%" >Chemistry</th>
               <th width="15%" >Biology</th>
               <th width="15%" >SST</th>
           </tr>
       ';
       while($row = mysqli_fetch_array($result))
       {
            $output .= '
                 <tr>
                      <td>'.$row["name"].'</td>
                      <td>'.$row["Physics"].'</td>
                      <td>'.$row["Maths"].'</td>
                      <td>'.$row["Chemistry"].'</td>
                      <td>'.$row["Biology"].'</td>
                      <td>'.$row["SST"].'</td>
                 </tr>
            ';
       }
       $output .= '</table>';
       echo $output;
  }
  else
  {
       echo 'errorx';
  }
 }
  else
{
     echo "errory";
}
 ?>

但是导入的 csv 文件会在表中插入空值 因为分配给我的所有 csv 文件的格式都完全相同:

,,,,,,,,
,,,,,,,,
,,,,,,,,
,,,,,,,,
,,,,,,,,
,,,,,,,,
,,,,,,,,
,,,,,,,,
,,,,,,,,
,,,Fields,Physics~75,Maths~50,Chemistry~65,Bio~85,SST~100
,,,Name1,10,25,35,42,62
,,,Name2,80,45,45,45,25
,,,Name3,63,25,63,36,36
,,,Name4,82,36,75,48,42
,,,Name5,45,45,78,25,24
,,,Name6,36,36,15,75,36
,,,Name7,99,45,24,24,45
,,,Name8,45,85,85,85,96

我尝试了多个转义函数,但没有一个有效,并且也很难删除字段行。

【问题讨论】:

  • 那么当Name为空或者等于Fields时使用php continue语句?
  • 我修复了这个VALUES ('$name', '$Physics', SQLInjection 问题
  • @danblack ajax 调用中断,当我使用 continue 时没有任何反应;
  • @ArtisticPhoenix 当然,我会解决的。谢谢:)

标签: php mysql ajax csv


【解决方案1】:

为此:

csv 文件在表中插入空值
,,,,,,,,
,,,,,,,,

检查空像这样(过滤数组后):

while($row = fgetcsv($file_data)) //['','','','','']
{
   if(empty(array_filter($row))) continue; //[] after array_filter
   ///...
}

对于Fields,你基本上做同样的事情,除了在条件中寻找类似的东西

while($row = fgetcsv($file_data)) //['','','','','']
{
   if(empty(array_filter($row)) || $row[3]=='Fields') continue; //[] after array_filter
   ///...
}

您可以只查找empty($row[3]),但这只是告诉您该列是空的,而不是整行。

更新

我想通了,考虑到我拥有的 csv 文件的类型,这是我的代码中的一个愚蠢的索引错误。

如果你想要关联数组,使用标题中的键可以很容易地做到:如果标题正确并且行具有正确的列数,并且标题是唯一的

   $headers = fgetcsv($file_data);   //['header1','header2']
   while($data = fgetcsv($file_data)) //['data1','data2']
   {
       $row = array_combine($headers,$data); //['header1'=>'data1','header2'=>'data2']

数组组合必须具有与值相同数量的键才能起作用(两个数组必须具有相同的长度)。在典型的 CSV 中,“应该”总是如此,以我的经验并非如此。但是,当不是该行时,怀疑它的数据转移到了错误的列(在正常情况下,没有数组组合)。所以你必须问问自己是否可以接受。

希望对你有帮助。

【讨论】:

  • 我已经尝试过了,但是每当我使用 continue 时;它要么给出 ma 语法错误,要么 ajax 调用中断并且没有任何反应
  • @zetastreak - 缺少) 抱歉...基本语法错误if(empty(array_filter($row)) continue; vs if(empty(array_filter($row))) continue;
  • @ArtisticPhoenix 是的,这是一种更好的方法。非常感谢:)
  • 我用 CSV 做一些事情,用这种方式重新映射标题也是可能的(但很棘手)。例如,我们有客户端设置设置,他们可以将我们的文件头从 name 更改为 ...fullname。但在我的代码中,它总是name,因为我将它们映射到那个。
【解决方案2】:

我想通了,考虑到我拥有的 csv 文件的类型,这是我的代码中的一个愚蠢的索引错误。 我加了

if ($row[3]=='Fields' || $row[3]=='') continue;

它奏效了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    • 2013-08-08
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 2017-02-13
    相关资源
    最近更新 更多