使用ajax和php在mysql db中导入csv

时间:2019-03-18 23:09:05

标签: php mysql ajax csv

我正在做一个小型项目,该项目通过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

我尝试了多种转义功能,但没有一个起作用,而且删除字段行也变得困难。

2 个答案:

答案 0 :(得分:0)

为此:

  

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中,这种情况“应该”总是这样,以我的经验却并非如此。但是,如果不是该行,则可能会将其数据移至错误的列(通常情况下,不使用数组组合)。因此,您必须问自己是否同意。

无论如何希望它会有所帮助。

答案 1 :(得分:0)

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

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

成功了。