user3469896
user3469896

Reputation: 43

csv download issue using php

I am trying to create a CSV file, so far my csv file downloads but it is blank.

<?php
include('connect.php');

//header to give the order to the browser
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=exported-data.csv');

// Gets users information of who's logged in
$query = "SELECT * FROM expenses";
$result = mysqli_query($db_connection, $query);

while ($dbRow = mysqli_fetch_array($result))
{
    $id = $dbRow["id"];
    $user_id = $dbRow["user_id"];
    $amount = $dbRow["amount"];
    $currency = $dbRow["currency"];
    $type = $dbRow["type"];
    $description = $dbRow["description"];
    $project_id = $dbRow["project_id"];
    $submission = $dbRow["submission"];
    $status = $dbRow["status"];
}

if ($rows)
{
    getcsv(array_keys($rows));
}
while($rows)
{
    getcsv($rows);
    $rows = mysqli_fetch_assoc($query);
}

// get total number of fields present in the database
function getcsv($no_of_field_names)
{
    $separate = '';


// do the action for all field names as field name
    foreach ($no_of_field_names as $field_name)
    {
        if (preg_match('/\\r|\\n|,|"/', $field_name))
        {
            $field_name = '' . str_replace('', $field_name) . '';
        }
        echo $separate . $field_name;

//sepearte with the comma
        $separate = ',';
    }

//make new row and line
    echo "\r\n";
}
?>

Upvotes: 1

Views: 100

Answers (1)

Lo&#239;c
Lo&#239;c

Reputation: 11942

<?php
include('connect.php');

//header to give the order to the browser
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=exported-data.csv');

// Gets users information of who's logged in
$query = "SELECT * FROM expenses";
$result = mysqli_query($db_connection, $query);

$first = true;
while ($dbRow = mysqli_fetch_array($result, MYSQL_ASSOC))
{
  if($first){
     $first = false;
     echo implode(',', array_keys($dbRow));
     echo "\r\n";
  }
  echo implode(',', $dbRow);
  echo "\r\n";
}
?>

Upvotes: 1

Related Questions