Adrian
Adrian

Reputation: 2291

Exporting data from sql with php to excel

I am trying to export sql to csv with php and this is what I managed to do. It works well without 2 things: 1. Before the sql data that is outputted in the csv I get the HTML code of the current page for some reason. 2. How can I change the table header rows? Want to rename the table header column in the csv.

$result = $db->query("SELECT * FROM user_history WHERE member_id = '$user_id'");
$num_fields = $result->field_count;
$headers = array();
$headers[] = "Number";
for($i = 0; $i < $num_fields; $i++ ) {
    $Obj = $result->fetch_field_direct($i);
    $headers[] = $Obj->name."\t";
}
$current_date = date("y/m/d");
$filename = "MyFileName" . $current_date . ".csv";
$fp = fopen('php://output', 'w');
if ($fp && $result) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename='.$filename);
    header('Pragma: no-cache');
    header('Expires: 0');
    echo "Title of Your CSV File\n\n";
    // Write mysql headers to csv
    fputcsv($fp, $headers);
    $row_tally = 0;
    // Write mysql rows to csv
    while ($row = $result->fetch_array(MYSQLI_NUM)) {
    $row_tally = $row_tally + 1;
    echo $row_tally.",";
        fputcsv($fp, array_values($row));
    }
    die;
}

Upvotes: 1

Views: 1750

Answers (1)

Paul Carlton
Paul Carlton

Reputation: 2993

fetch_field_direct returns an object with no __toString() method. According to this you need to change the code:

$header .= $result->fetch_field_direct($i)."\\t";

To:

$Obj = $result->fetch_field_direct($i);
$header .= $Obj->name."\t";

Secondly if you print "\\t" then you will literally get \t. print "\t"; will give you the tab character.

Upvotes: 1

Related Questions