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

I'm trying to search for some data then download it as CSV file, but when I click download button to download the data I have found, it's writing all my HTML code at the beginning of the file then it writes my data in the downloaded file. So how can I get only my data without writing the html code with it?.

Code

<?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;

?>
doumi0737
doumi0737 是的,如果我单独运行download.php,它将以正确的格式下载
一年多之前 回复
duanlu0386
duanlu0386 如果你直接通过在浏览器中输入url来直接下载.php你能下载csv吗?
一年多之前 回复

1个回答

The whole problem is then that you echo some html and inside it include 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';
  }

just put a link to the download.php instead of including it.

  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>';
  }

If you want to redirect user after submitting form to the download.php automatically then you may use attribute action in form. See how it is done HTML Attribute where a redirection is set to the page /action_page.php.

duanlu9557
duanlu9557 是的,我做了,它仍然是同样的问题
一年多之前 回复
doupo5178
doupo5178 但是你删除了这行包括'download.php'; ?
一年多之前 回复
dshmkgq558192365
dshmkgq558192365 即使我放了链接,它仍然是同样的问题
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐