PHP-导出CSV函数为每个条目重复标题

时间:2018-11-12 21:38:54

标签: php mysql csv

我们正在创建一个将数据从表导出到CSV的函数。但是,代码似乎重复了我们为插入CSV的每一行设置的标头,因此最终看起来像这样:

csv data (the red lines are blocked out data but you can see how the headers repeat for each row)

这是我们创建导出的代码:

//inserts data into import table
$sql = "INSERT into import (suid, studentName, studentEmail, studentAffiliation, studentProgram, studentEduLevel) values ('$suid', '$studentName', '$studentEmail', '$studentAffiliation', '$studentProgram', '$studentEduLevel')";
if (!$fail) {

    if (mysqli_multi_query($csvDatabase, $sql)) {
            //once imported properly, export csv

        $query = "SELECT suid, studentName, studentEmail, studentAffiliation, studentProgram, studentEduLevel from import ORDER BY id DESC LIMIT {$successCount}";  
          $result = mysqli_query($csvDatabase, $query); 
                if ($result->num_rows > 0) {
                  header('Content-Type: text/csv; charset=utf-8');  
                  header('Content-Disposition: attachment; filename=data-export.csv'); 
                    $output = fopen("php://output", "w"); 
                    $headers = array('SUID', 'Student Name', 'Student Email', 'Student Affiliation', 'studentProgram', 'Student Edu Level');
                    fputcsv($output, $headers); 
                     while($row = mysqli_fetch_assoc($result))  
                  {  
                         fputcsv($output, $row);
                  }  
                  fclose($output); 
                    //then delete records in database
                $deletesql = "DELETE FROM import ORDER BY id DESC LIMIT {$successCount}";
                    if (mysqli_query($csvDatabase, $deletesql)) {
                        //echo "Record deleted successfully";
                    } else {
                        echo "Error deleting record: " . mysqli_error($csvDatabase);
                    }

        }


    } else {
        echo "Error: " . $sql . "<br>" . mysqli_error($csvDatabase);
    }
 }

关于代码中重复标题的任何想法?

编辑:完整代码,省略服务器信息:

<?php
require_once('connection.php');

$successCount = 0;

if(isset($_POST['submit'])){

$filename = $_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0) {
for($i=0; $i<count($filename); $i++) {
    $file = $filename[$i];
    //open file in read only
    $files = fopen($file, "r");
    //skips first line
    fgets($files); 
    //get data from csv & uses comma to find separate values
        while (($getData = fgetcsv($files, 0, ",")) !== FALSE)
         {
            $fail = FALSE;
            //store SUID from 2nd line in csv
            $suid = $getData[0];
            if (strlen($suid) === 9 && ctype_digit($suid) ) {
            // start ldap look up
            $server="***";
            $basedn="***";

            //Connect to server
            $ds=ldap_connect($server);

            if ($ds) {
                //bind with our special account that retrieves more attributes
                $ldaprdn  = '***';     // ldap rdn or dn
                $ldappass = '***';  // associated password
                $r=ldap_bind($ds,$ldaprdn,$ldappass);    // this is an authenticated bind
                if (substr($suid, 0, 1) === ";" || is_numeric($suid)) {
                        if ($r) {
                            //filter to all objectclasses that the SUID we are looking for
                            $filter = "(&(objectClass=*)(syrEduSUID={$suid}))";

                            //We are only interested in retrieving these attributes
                            $justthese = array("displayName", "syrEduLevel", "syrEduProgramDesc", "syrEduProgram", "mail", "eduPersonPrimaryAffiliation", "eduPersonAffiliation" );

                            // Search SUID
                            $sr=ldap_search($ds, $basedn, $filter, $justthese );
                            //Need to test if the search succeeded. FALSE value means it failed
                            //if ($sr!==FALSE) {
                                //Search found something. Now return Attributes and their values - note, there can be multiple values per attribute. We need to make sure the search only returned one result

                                $entry = ldap_get_entries($ds, $sr);
                                // if we have only one result, return the values, if not, we have a problem

                                if ($entry["count"] == 1) {
                                // get student name and email from suid

                                $studentName = mysqli_real_escape_string($csvDatabase, $entry[0]['displayname'][0]);
                                $studentEmail = mysqli_real_escape_string($csvDatabase, $entry[0]['mail'][0]);
                                $studentAffiliation = mysqli_real_escape_string($csvDatabase, $entry[0]['edupersonprimaryaffiliation'][0]);
                                $studentProgram = mysqli_real_escape_string($csvDatabase, $entry[0]['syreduprogramdesc'][0]);
                                $studentEduLevel = mysqli_real_escape_string($csvDatabase, $entry[0]['syredulevel'][0]);

                                    $successCount++;

                                // close ldap
                                ldap_close($ds);

                                } else {
                                    $msg  = "Ldap search returned 0 or more than one result";
                                    $fail = TRUE;
                                }

                        //} else {
                        //    $msg  = "Search failed";
                        //    $fail = TRUE;
                        //}
                    }
                } else {
                    $msg  = "Bind failed";
                    $fail = TRUE;
                }
            } else {
                $msg  = "LDAP connection failed";
                $fail = TRUE;
            }

                        //inserts data into import table
                        $sql = "INSERT into import (suid, studentName, studentEmail, studentAffiliation, studentProgram, studentEduLevel) values ('$suid', '$studentName', '$studentEmail', '$studentAffiliation', '$studentProgram', '$studentEduLevel')";
                        if (!$fail) {

                            if (mysqli_multi_query($csvDatabase, $sql)) {
                                    //once imported properly, export csv

                                $query = "SELECT suid, studentName, studentEmail, studentAffiliation, studentProgram, studentEduLevel from import ORDER BY id DESC LIMIT {$successCount}";  
                                  $result = mysqli_query($csvDatabase, $query); 
                                        if ($result->num_rows > 0) {
                                          header('Content-Type: text/csv; charset=utf-8');  
                                          header('Content-Disposition: attachment; filename=data-export.csv'); 
                                            $output = fopen("php://output", "w"); 
                                            $headers = array('SUID', 'Student Name', 'Student Email', 'Student Affiliation', 'studentProgram', 'Student Edu Level');
                                            fputcsv($output, $headers); 
                                             while($row = mysqli_fetch_assoc($result))  
                                          {  
                                                 fputcsv($output, $row);
                                          }  
                                          fclose($output); 
                                            //then delete records in database
                                        $deletesql = "DELETE FROM import ORDER BY id DESC LIMIT {$successCount}";
                                            if (mysqli_query($csvDatabase, $deletesql)) {
                                                //echo "Record deleted successfully";
                                            } else {
                                                echo "Error deleting record: " . mysqli_error($csvDatabase);
                                            }

                                }


                            } else {
                                echo "Error: " . $sql . "<br>" . mysqli_error($csvDatabase);
                            }
                         }
                }
        }

    //closes file    
    fclose($files); 
     }
} else {
    echo "You did not upload a CSV file or the CSV file is blank.";
}
} else {
?>

1 个答案:

答案 0 :(得分:0)

正如IdontDownVote指出的那样,代码被放置在每个文件循环中。一旦取出并放在fclose($ files)之后,它就不会重复标题。