如何从 php 中的当前会话获取 csv 文件?

How to get csv file from current session in php?

逻辑是“从当前用户填写的表单中获取信息,插入数据库并以 .csv 格式文件将其返回给他(给用户)”。但在 csv 文件中,数据重复两次,如本问题底部所附的屏幕截图所示。如果你遇到过这样的情况,能帮帮我吗?

整个index.php:

  <?php

  session_start();
  $_SESSION['user'] = $_POST['first_name'];

  try {
       $db = new PDO('pgsql:host=localhost;dbname=test', 'someuser', '123456');
       $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  } catch(PDOException $e) {
      print $e->getMessage();
  }

  if($_SERVER['REQUEST_METHOD']=='POST') {
      if(validate()) {
          process();
      }
  } else {
      show();
  }

  function validate() {
      $phoneLength = strlen($_POST['phone']);
      if($phoneLength==11) {
              return true;
      } else {
          print "Phone number must contain more than $phoneLength characters.";
      }
  }

  function process(){
      try{
          // Insert into db
          $stmt = $db->prepare("INSERT INTO personalInfo (first_name, last_name, email, phone) 
                            VALUES (?,?,?,?)");
          $stmt->execute(array($_POST['first_name'], $_POST['last_name'], 
                        $_POST['email'], $_POST['phone']));
    
      } catch(PDOException $e) {
          print $e->getMessage();
      }

      // Get file
      header('Content-type: text/csv');
      header('Content-disposition: attachment; filename: info.csv');

      $fh = fopen('php://output', 'wb');
      $q = $db->query("SELECT * FROM personalInfo WHERE first_name = '{$_SESSION['user_fname']}' ");
      while ($row = $q->fetch()) {
          fputcsv($fh, $row);
      }
  }

  function show(){
      print<<<_HTML_
      <form method='POST' action='$_SERVER[PHP_SELF]'>
          <input name='first_name' type='text' placeholder='Your first name' required><br>
          <input name='last_name' type='text' placeholder='Your last name' required><br>
          <input name='email' type='email' placeholder='Your e-mail' required><br>
          <input name='phone' type='number' placeholder='Your phone number' required><br>
         <input type='submit' value='GET'>
     </form>
     _HTML_;
  }

问题区域:

      // Get file
      header('Content-type: text/csv');
      header('Content-disposition: attachment; filename: info.csv');

      $fh = fopen('php://output', 'wb');
      $q = $db->query("SELECT * FROM personalInfo WHERE first_name = '{$_SESSION['user_fname']}' ");
      while ($row = $q->fetch()) {
          fputcsv($fh, $row);
      }

显示: Double writing each column data 为什么?

这在文档中有解释。 manual for the PDO fetch function 说它接受一个名为“mode”的可选参数,这就是它对那个选项的描述:

mode: Controls how the next row will be returned to the caller ... defaults to PDO::FETCH_BOTH

PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set

所以你得到了两次相同的数据,因为 PDO returns 它两次。 $row 将包含相同数据的数组 - 一次在关联(命名)字段中,一次在编号字段中。然后 fputcsv 不加区别地处理整个数组。

为了您的目的,一个基本的编号数组就足够了,所以您可以只告诉 PDO return:

$row = $q->fetch(PDO::FETCH_NUM)