phpfputcsv

Not understanding the output of fputcsv() function in PHP


I'm not understanding the output I get from this query. Each column is being duplicated, so instead of getting the 7 columns requested, I'm getting 14, each next to its duplicate, but with no header. Here is my code:

<?php
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=netID2807.csv');

// create a file pointer connected to the output stream, usually downloads
$output = fopen('php://output', 'w');

// output the column headings
fputcsv($output, array('Callsign', 'First Name', 'Last Name', 'Time In', 'Time Out', 'County', 'State'));

// go get the data
require_once "dbConnectDtls.php";  // Access to MySQL

$sql = "SELECT callsign, Fname, Lname, logdate, timeout, county, state 
          FROM NetLog 
         WHERE netID = 2807";

foreach($db_found->query($sql) as $row) {
    fputcsv($output, $row);
}
?>

Why are all my columns being duplicated, and how do I fix it?


Solution

  • It looks like your fetch is defaulting to retrieve both associative and numeric-indexed arrays, so it outputs both to the file. You could try specifying that it is only to retrieve either one or the other. I can't see how your data is actually fetched, that must be in your include file.

    If you're on mysqli, fetch_array() defaults to MYSQLI_BOTH which will do as your comment suggests. Instead, specify MYSQLI_ASSOC or MYSQLI_NUM when the data is retrieved.