You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
36 lines
941 B
36 lines
941 B
<?php |
|
|
|
function query_to_csv(string $query, bool $print_header = false, string $filename = 'result') { |
|
$pdo = new PDO('mysql:host=localhost;dbname=observer', 'observerro', 'KhOp1w8U'); |
|
|
|
$statement = $pdo->prepare($query); |
|
|
|
require('http_errors.php'); |
|
|
|
if (!$statement->execute()) { |
|
HttpResponse::internal_server_error()->set_and_exit(); |
|
} |
|
|
|
$out = fopen('php://output', 'w'); |
|
if ($out === false) { |
|
HttpResponse::internal_server_error()->set_and_exit(); |
|
} |
|
|
|
if (substr($filename, -4) !== '.csv') { |
|
$filename = $filename . '.csv'; |
|
} |
|
|
|
header('Content-Type: text/csv'); |
|
header('Content-Disposition: filename=' . $filename); |
|
if ($print_header) { |
|
$columns = array(); |
|
for ($i = 0; $i < $statement->columnCount(); $i++) { |
|
$columns[] = $statement->getColumnMeta($i)['name']; |
|
} |
|
fputcsv($out, $columns); |
|
} |
|
|
|
while ($row = $statement->fetch(PDO::FETCH_NUM)) { |
|
fputcsv($out, $row); |
|
} |
|
}
|
|
|