Skip to content

Commit 895a638

Browse files
authored
Merge pull request #64 from iazaran/export_to_csv
Export to csv
2 parents dd12a83 + 2cf74ca commit 895a638

File tree

5 files changed

+61
-1
lines changed

5 files changed

+61
-1
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ Register an event listener and trigger it when needed
7171
Run R script (if you have R installed)
7272
- **HttpClient::cURL(...)**
7373
Run cURL script to send a request
74+
- **CsvGenerator::exportCSV(...)**
75+
Export a specific table from DB to a CSV file
7476

7577
#### Run Web App:
7678
- Install docker and docker-compose if needed

composer.lock

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

public/assets/storage/file.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Enable to make it directly with Docker

src/App/CsvGenerator.php

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
<?php
2+
3+
namespace App;
4+
5+
/**
6+
* Class CsvGenerator
7+
* @package App
8+
*/
9+
class CsvGenerator
10+
{
11+
/**
12+
* Create a CSV file from a specific table on DB
13+
*
14+
* @param string $tableName
15+
* @return bool|void
16+
*/
17+
public static function exportCSV(string $tableName)
18+
{
19+
$path = $_SERVER['DOCUMENT_ROOT'] . '/assets/storage/' . $tableName . '.csv';
20+
$file = fopen($path, 'w') or die('Unable to write into file!');
21+
22+
$sql = "DESCRIBE $tableName";
23+
Database::query($sql);
24+
Database::execute();
25+
26+
$header = Database::fetchColumn();
27+
28+
fputcsv($file, $header);
29+
30+
$sql = "SELECT * FROM $tableName";
31+
Database::query($sql);
32+
Database::execute();
33+
34+
$rows = Database::fetchAll();
35+
foreach ($rows as $row) {
36+
fputcsv($file, $row);
37+
}
38+
39+
return true;
40+
}
41+
}

src/App/Database.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,22 @@ public static function fetchAll(): array|bool
125125
return self::$stmt->fetchAll(PDO::FETCH_ASSOC);
126126
}
127127

128+
/**
129+
* Get column names as array
130+
*
131+
* @return array|bool
132+
*/
133+
public static function fetchColumn(): array|bool
134+
{
135+
try {
136+
self::$stmt->execute();
137+
} catch (PDOException $exception) {
138+
echo 'PDO Error: ' . $exception->getMessage();
139+
}
140+
141+
return self::$stmt->fetchAll(PDO::FETCH_COLUMN);
142+
}
143+
128144
/**
129145
* Get single record as array
130146
*

0 commit comments

Comments
 (0)