+3 votes
304 views
in Web development by (242k points)
mysqli sql export as CSV/XLS

1 Answer

+4 votes
by (242k points)
 
Best answer

//create empty variable to be filled with export data

$csv_export = '';

// query to get data from database

$query = mysqli_query($mysqli, $sql);

$field = mysqli_field_count($mysqli);

// create line with field names

for($i = 0; $i < $field; $i++) {

    $csv_export.= mysqli_fetch_field_direct($query, $i)->name."\t";

}

// newline (seems to work both on Linux & Windows servers)

$csv_export.= '

';

// loop through database query and fill export variable

while($row = mysqli_fetch_array($query)) {

    // create line with field values

    for($i = 0; $i < $field; $i++) {

        $csv_export.= '"'.$row[mysqli_fetch_field_direct($query, $i)->name]."\"\t";

    }

    $csv_export.= '

';

}

// Export the data and prompt a csv file for download

    header("Content-type: application/octet-stream");

    header("Content-Disposition: attachment; filename=katalog-eserleri.xls");

    header("Pragma: no-cache");

    header("Expires: 0");

echo(chr(255).chr(254).iconv("UTF-8", "UTF-16LE//IGNORE", $csv_export) );

...