PHP - Export CSV Function Repeats Headers for Each Entry










0














We are creating a function that exports data from a table to a CSV. However, the code seems to repeat the headers we set for each row inserted into the CSV so it ends up looking like this:



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



Here is our code to do create the export:



//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);




Any ideas on what could be happening in the code to repeat the headers?



EDIT: Full code with omitted server information:



<?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) 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 {
?>









share|improve this question























  • This code doesn't look like it should repeat the header. What are you using to view the CSV? It looks like it's in a table or something. (Just wondering if it's possible that's what's duplicating the headers.)
    – Don't Panic
    Nov 12 '18 at 21:44










  • WARNING: When using mysqli you should be using parameterized queries and bind_param to add user data to your query. DO NOT use string interpolation or concatenation to accomplish this because you have created a severe SQL injection bug. NEVER put $_POST, $_GET or any user data directly into a query, it can be very harmful if someone seeks to exploit your mistake.
    – tadman
    Nov 12 '18 at 21:45










  • Note: The object-oriented interface to mysqli is significantly less verbose, making code easier to read and audit, and is not easily confused with the obsolete mysql_query interface. Before you get too invested in the procedural style it’s worth switching over. Example: $db = new mysqli(…) and $db->prepare("…") The procedural interface is an artifact from the PHP 4 era when mysqli API was introduced and should not be used in new code.
    – tadman
    Nov 12 '18 at 21:45










  • WARNING: Do not use mysqli_multi_query as it cannot be secured, it doesn't support placeholder values. This is a common attack vector, so the safest thing is to avoid using it at all costs.
    – tadman
    Nov 12 '18 at 21:45






  • 1




    your inside a per file loop
    – user10226920
    Nov 12 '18 at 21:56















0














We are creating a function that exports data from a table to a CSV. However, the code seems to repeat the headers we set for each row inserted into the CSV so it ends up looking like this:



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



Here is our code to do create the export:



//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);




Any ideas on what could be happening in the code to repeat the headers?



EDIT: Full code with omitted server information:



<?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) 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 {
?>









share|improve this question























  • This code doesn't look like it should repeat the header. What are you using to view the CSV? It looks like it's in a table or something. (Just wondering if it's possible that's what's duplicating the headers.)
    – Don't Panic
    Nov 12 '18 at 21:44










  • WARNING: When using mysqli you should be using parameterized queries and bind_param to add user data to your query. DO NOT use string interpolation or concatenation to accomplish this because you have created a severe SQL injection bug. NEVER put $_POST, $_GET or any user data directly into a query, it can be very harmful if someone seeks to exploit your mistake.
    – tadman
    Nov 12 '18 at 21:45










  • Note: The object-oriented interface to mysqli is significantly less verbose, making code easier to read and audit, and is not easily confused with the obsolete mysql_query interface. Before you get too invested in the procedural style it’s worth switching over. Example: $db = new mysqli(…) and $db->prepare("…") The procedural interface is an artifact from the PHP 4 era when mysqli API was introduced and should not be used in new code.
    – tadman
    Nov 12 '18 at 21:45










  • WARNING: Do not use mysqli_multi_query as it cannot be secured, it doesn't support placeholder values. This is a common attack vector, so the safest thing is to avoid using it at all costs.
    – tadman
    Nov 12 '18 at 21:45






  • 1




    your inside a per file loop
    – user10226920
    Nov 12 '18 at 21:56













0












0








0







We are creating a function that exports data from a table to a CSV. However, the code seems to repeat the headers we set for each row inserted into the CSV so it ends up looking like this:



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



Here is our code to do create the export:



//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);




Any ideas on what could be happening in the code to repeat the headers?



EDIT: Full code with omitted server information:



<?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) 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 {
?>









share|improve this question















We are creating a function that exports data from a table to a CSV. However, the code seems to repeat the headers we set for each row inserted into the CSV so it ends up looking like this:



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



Here is our code to do create the export:



//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);




Any ideas on what could be happening in the code to repeat the headers?



EDIT: Full code with omitted server information:



<?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) 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 {
?>






php mysql csv






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 12 '18 at 21:51

























asked Nov 12 '18 at 21:38









ESE Technical Services

32




32











  • This code doesn't look like it should repeat the header. What are you using to view the CSV? It looks like it's in a table or something. (Just wondering if it's possible that's what's duplicating the headers.)
    – Don't Panic
    Nov 12 '18 at 21:44










  • WARNING: When using mysqli you should be using parameterized queries and bind_param to add user data to your query. DO NOT use string interpolation or concatenation to accomplish this because you have created a severe SQL injection bug. NEVER put $_POST, $_GET or any user data directly into a query, it can be very harmful if someone seeks to exploit your mistake.
    – tadman
    Nov 12 '18 at 21:45










  • Note: The object-oriented interface to mysqli is significantly less verbose, making code easier to read and audit, and is not easily confused with the obsolete mysql_query interface. Before you get too invested in the procedural style it’s worth switching over. Example: $db = new mysqli(…) and $db->prepare("…") The procedural interface is an artifact from the PHP 4 era when mysqli API was introduced and should not be used in new code.
    – tadman
    Nov 12 '18 at 21:45










  • WARNING: Do not use mysqli_multi_query as it cannot be secured, it doesn't support placeholder values. This is a common attack vector, so the safest thing is to avoid using it at all costs.
    – tadman
    Nov 12 '18 at 21:45






  • 1




    your inside a per file loop
    – user10226920
    Nov 12 '18 at 21:56
















  • This code doesn't look like it should repeat the header. What are you using to view the CSV? It looks like it's in a table or something. (Just wondering if it's possible that's what's duplicating the headers.)
    – Don't Panic
    Nov 12 '18 at 21:44










  • WARNING: When using mysqli you should be using parameterized queries and bind_param to add user data to your query. DO NOT use string interpolation or concatenation to accomplish this because you have created a severe SQL injection bug. NEVER put $_POST, $_GET or any user data directly into a query, it can be very harmful if someone seeks to exploit your mistake.
    – tadman
    Nov 12 '18 at 21:45










  • Note: The object-oriented interface to mysqli is significantly less verbose, making code easier to read and audit, and is not easily confused with the obsolete mysql_query interface. Before you get too invested in the procedural style it’s worth switching over. Example: $db = new mysqli(…) and $db->prepare("…") The procedural interface is an artifact from the PHP 4 era when mysqli API was introduced and should not be used in new code.
    – tadman
    Nov 12 '18 at 21:45










  • WARNING: Do not use mysqli_multi_query as it cannot be secured, it doesn't support placeholder values. This is a common attack vector, so the safest thing is to avoid using it at all costs.
    – tadman
    Nov 12 '18 at 21:45






  • 1




    your inside a per file loop
    – user10226920
    Nov 12 '18 at 21:56















This code doesn't look like it should repeat the header. What are you using to view the CSV? It looks like it's in a table or something. (Just wondering if it's possible that's what's duplicating the headers.)
– Don't Panic
Nov 12 '18 at 21:44




This code doesn't look like it should repeat the header. What are you using to view the CSV? It looks like it's in a table or something. (Just wondering if it's possible that's what's duplicating the headers.)
– Don't Panic
Nov 12 '18 at 21:44












WARNING: When using mysqli you should be using parameterized queries and bind_param to add user data to your query. DO NOT use string interpolation or concatenation to accomplish this because you have created a severe SQL injection bug. NEVER put $_POST, $_GET or any user data directly into a query, it can be very harmful if someone seeks to exploit your mistake.
– tadman
Nov 12 '18 at 21:45




WARNING: When using mysqli you should be using parameterized queries and bind_param to add user data to your query. DO NOT use string interpolation or concatenation to accomplish this because you have created a severe SQL injection bug. NEVER put $_POST, $_GET or any user data directly into a query, it can be very harmful if someone seeks to exploit your mistake.
– tadman
Nov 12 '18 at 21:45












Note: The object-oriented interface to mysqli is significantly less verbose, making code easier to read and audit, and is not easily confused with the obsolete mysql_query interface. Before you get too invested in the procedural style it’s worth switching over. Example: $db = new mysqli(…) and $db->prepare("…") The procedural interface is an artifact from the PHP 4 era when mysqli API was introduced and should not be used in new code.
– tadman
Nov 12 '18 at 21:45




Note: The object-oriented interface to mysqli is significantly less verbose, making code easier to read and audit, and is not easily confused with the obsolete mysql_query interface. Before you get too invested in the procedural style it’s worth switching over. Example: $db = new mysqli(…) and $db->prepare("…") The procedural interface is an artifact from the PHP 4 era when mysqli API was introduced and should not be used in new code.
– tadman
Nov 12 '18 at 21:45












WARNING: Do not use mysqli_multi_query as it cannot be secured, it doesn't support placeholder values. This is a common attack vector, so the safest thing is to avoid using it at all costs.
– tadman
Nov 12 '18 at 21:45




WARNING: Do not use mysqli_multi_query as it cannot be secured, it doesn't support placeholder values. This is a common attack vector, so the safest thing is to avoid using it at all costs.
– tadman
Nov 12 '18 at 21:45




1




1




your inside a per file loop
– user10226920
Nov 12 '18 at 21:56




your inside a per file loop
– user10226920
Nov 12 '18 at 21:56












1 Answer
1






active

oldest

votes


















0














As pointed out by IdontDownVote, the code was placed inside the per file loop. Once taken out and placed after fclose($files), it doesn't repeat the headers.






share|improve this answer




















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53270482%2fphp-export-csv-function-repeats-headers-for-each-entry%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    As pointed out by IdontDownVote, the code was placed inside the per file loop. Once taken out and placed after fclose($files), it doesn't repeat the headers.






    share|improve this answer

























      0














      As pointed out by IdontDownVote, the code was placed inside the per file loop. Once taken out and placed after fclose($files), it doesn't repeat the headers.






      share|improve this answer























        0












        0








        0






        As pointed out by IdontDownVote, the code was placed inside the per file loop. Once taken out and placed after fclose($files), it doesn't repeat the headers.






        share|improve this answer












        As pointed out by IdontDownVote, the code was placed inside the per file loop. Once taken out and placed after fclose($files), it doesn't repeat the headers.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 12 '18 at 22:07









        ESE Technical Services

        32




        32



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53270482%2fphp-export-csv-function-repeats-headers-for-each-entry%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Barbados

            How to read a connectionString WITH PROVIDER in .NET Core?

            Node.js Script on GitHub Pages or Amazon S3