如何从数据库中导出数据并以正确格式将其导入CSV文件

时间:2019-04-01 15:44:02

标签: php html

我正在尝试搜索一些数据,然后将其下载为CSV文件,但是当我单击“下载”按钮下载找到的数据时,它将在文件的开头写入所有HTML代码,然后将其写入数据在下载的文件中。那么,如何在不编写html代码的情况下仅获取数据呢?

代码

<?php 
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "CNG492";
    $message = "";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
?>
<html>
<head>
    <title>Search By Keyword</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title> Upload Data Page</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
  <style>
  table {
    font-family: Raleway;
    border-collapse: collapse;
    width: 100%;
  }

  td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
  }
  body 
  {
    background-color: #722f37;
  }

  .btn{
    background-color: #722f37;
    color: #ffffff;
    border: none;
    padding: 10px 20px;
    font-size: 17px;
    font-family: Raleway;
    cursor: pointer;
  }
  .box
  {
    background-color: #ffffff;
    margin: 100px auto;
    font-family: Raleway;
    padding: 40px;
    width: 80%;
    min-width: 300px;
  }

  .has-error
  {
   border-color:#cc0000;
   background-color:#ffff99;
  }
  .form{display:block;width:100%;height:34px;padding:6px 12px;font-size:14px;line-height:1.42857143;color:#555;background-color:#fff;background-image:none;border:1px solid #ccc;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition:border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}
  </style>
</head>
<body>
    <div class="container box">
        <br />
     <h1 align="center">Search</h1><br />
     <form method="post" id="search_form">
       <div class="form-group">
         <label>Keyword:</label>
         <input type="text" name="keyword" id="keyword" class="form-control"/>
         <span id="error_keyword" class="text-danger"></span>
       </div>
       <div align="inline">
         <button type="button" name="find_keyword" id="find_keyword" class="btn btn-dark btn-lg">Find</button>
         <a href="advanced_search.php"><button type="button" name="adv_search" id="adv_search" class="btn btn-dark btn-lg">Advance Search</button></a>
       </div>
       <br>
       <?php
    if(isset($_POST["keyword"])){
      $keyword = mysqli_real_escape_string($conn,$_POST["keyword"]);
      $dataset_result = -1;
      //Search for keyword inside tables
      $search_query = "SELECT dataset_id,title,description FROM dataset WHERE dataset_id IN (SELECT dataset_id FROM dataset WHERE title LIKE '%{$keyword}%' OR collector LIKE '%{$keyword}%' OR description LIKE '%{$keyword}%' OR d_procedure LIKE '%{$keyword}%'
  UNION DISTINCT
  SELECT dataset_id FROM group_table WHERE group_desc LIKE '%{$keyword}%'
  UNION DISTINCT
  SELECT dataset_id FROM material WHERE m_type LIKE '%{$keyword}%' OR URI LIKE '%{$keyword}%'
  UNION DISTINCT
  SELECT dataset_id FROM task WHERE type LIKE '%{$keyword}%' OR description LIKE '%{$keyword}%'
  UNION DISTINCT
  SELECT dataset_id FROM dataset WHERE eq_id IN (SELECT e.eq_id FROM tracker t,equipment e WHERE t.tracker_id=e.tracker_id AND (t.brand LIKE '%{$keyword}%' OR t.model LIKE '%{$keyword}%')))";


    $search_result = $conn->query($search_query);
    $dataset_result = mysqli_num_rows($search_result);

    if ($dataset_result == 0) {
        echo '

          <div class="alert alert-success">
            No reasults found.
          </div>

        ';
    }else{

      echo '
              <h4>Results</h4>
              <table>
              <tr>
                <th>Title</th>
                <th>Description</th>
                <th>Dowload Link</th>
              </tr>';
        while ($row = mysqli_fetch_assoc($search_result)) {
            echo '<tr>
                  <td>'.$row["title"].'</td>
                  <td>'.$row["description"].'</td>
                  <td><button type="submit" name="download" id="download" value="'.$row["dataset_id"].'">Dowload</button></td>
                </tr>';
        }
      echo '</table>
          ';
        if (isset($_POST["download"])) {
          $d_id = $_POST["download"];
          include 'download.php';
      }
    }
  }
    mysqli_close($conn);
?>
     </form>
    </div>
</body>
</html>

<script>
    $(document).ready(function() {
    $('#find_keyword').click(function(){
      var error_keyword = '';

      if($.trim($('#keyword').val()).length == 0){
        error_keyword = 'Enter a keyword please.'
        $('#error_keyword').text(error_keyword);
         $('#keyword').addClass('has-error');
      }else
      {
        error_keyword = '';
        $('#error_keyword').text(error_keyword);
        $('#keyword').removeClass('has-error');
      }
      if(error_keyword != ''){
        return false;
      }else{
        $('#find_keyword').attr("disabled", "disabled");
        $(document).css('cursor', 'prgress');
        $("#search_form").submit();
      }
    });
  })
</script>

Download.php

<?php
//include database configuration file
 $servername = "localhost";
  $username = "root";
  $password = "";
  $dbname = "CNG492";
  $message = "";

   // Create connection
  $connect = new mysqli($servername, $username, $password, $dbname);

  // Check connection
  if ($connect->connect_error) {
      die("Connection failed: " . $conn->connect_error);
  }
//get records from database
$query = $connect->query("SELECT * FROM dataset");

if($query->num_rows > 0){
    $delimiter = ",";
    $filename = "members_" . date('Y-m-d') . ".csv";

    //create a file pointer
    $f = fopen('php://memory', 'w');

    //set column headers
    $fields = array('title', 'description');
    fputcsv($f, $fields, $delimiter);

    //output each row of the data, format line as csv and write to file pointer
    while($row = $query->fetch_assoc()){
        $lineData = array($row['title'], $row['description']);
        fputcsv($f, $lineData, $delimiter);
    }

    //move back to beginning of file
    fseek($f, 0);

    //set headers to download file rather than displayed
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $filename . '";');

    //output all remaining data on a file pointer
    fpassthru($f);
}
exit;

?>

1 个答案:

答案 0 :(得分:0)

然后整个问题是,您回显了一些html,并且其中包含download.php

  echo '
          <h4>Results</h4>
          <table>
          <tr>
            <th>Title</th>
            <th>Description</th>
            <th>Dowload Link</th>
          </tr>';
    while ($row = mysqli_fetch_assoc($search_result)) {
        echo '<tr>
              <td>'.$row["title"].'</td>
              <td>'.$row["description"].'</td>
              <td><button type="submit" name="download" id="download" value="'.$row["dataset_id"].'">Dowload</button></td>
            </tr>';
    }
  echo '</table>
      ';
    if (isset($_POST["download"])) {
      $d_id = $_POST["download"];
      include 'download.php';
  }

只需放置一个指向download.php的链接,而不要包含它。

  echo '
          <h4>Results</h4>
          <table>
          <tr>
            <th>Title</th>
            <th>Description</th>
            <th>Dowload Link</th>
          </tr>';
    while ($row = mysqli_fetch_assoc($search_result)) {
        echo '<tr>
              <td>'.$row["title"].'</td>
              <td>'.$row["description"].'</td>
              <td><button type="submit" name="download" id="download" value="'.$row["dataset_id"].'">Dowload</button></td>
            </tr>';
    }
  echo '</table>
      ';
    if (isset($_POST["download"])) {
      $d_id = $_POST["download"];
      echo '<a href="download.php">Download File</a>';
  }

如果要在将表单自动提交到download.php之后重定向用户,则可以在表单中使用属性action。 查看如何完成HTML Attribute,其中将重定向设置到页面/action_page.php