0

I am trying to export a csv file with empty fields via php using select statements but the empty columns are not being included in the csv output.

    $query = "SELECT client_last_name,'','','','', client_first_name FROM billing_line_item"; 


   $result = mysqli_query($connection, $query);

   if (!$result) {
    die("Query Failed" . mysqli_error($connection));
   } else {

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

    $output = fopen('php://output', 'w');         
    fputs($output, implode($header1, ',')."\n");
    while ($row = mysqli_fetch_assoc($result)) {
        fputs($output,implode($row, ',')."\n");
    }
    fclose($output);
    exit();
}

The output in my csv file is the following:

Print_R of Array:
Array
(
[client_last_name] => LastName
[] => 
[client_first_name] => FirstName
)

Output:  LastName,,FirstName
Expecting: LastName,,,,,FirstName

1 Answer 1

1

Since you didn't assign any aliases to the empty columns, they're all named with the same empty string. But an associative array can't have duplicate keys, so you only get one empty column when you use mysqli_fetch_assoc. Instead, use mysqli_fetch_row, which returns a numeric-indexed array.

Alternatively you could assign aliases to the empty columns.

$query = "SELECT client_last_name,'' AS empty1, '' AS empty2, '' AS empty3, '' AS empty4, client_first_name FROM billing_line_item"; 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.