Skip to content

Commit f4150d0

Browse files
committed
Add script to convert users table to csv
1 parent c78cf21 commit f4150d0

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

bin/bnetdocs-users-csv.php

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#!/usr/bin/env php
2+
<?php /* vim: set expandtab colorcolumn= tabstop=4 shiftwidth=4 softtabstop=4: */
3+
/**
4+
* @project bnetdocs-web <https://github.com/BNETDocs/bnetdocs-web/>
5+
*
6+
* Connects to the users table and prints a csv replica to stdout.
7+
*/
8+
9+
function exit_line($line) { fwrite(STDERR, $line . PHP_EOL); exit(1); }
10+
11+
$csv = fopen('php://stdout', 'w');
12+
if (!$csv) { exit_line('Failed to open stdout for writing'); }
13+
14+
$cfg = file_get_contents(__DIR__ . '/../etc/config.phoenix.json');
15+
if (!$cfg) { exit_line('Failed to open and read config'); }
16+
17+
$cfg = json_decode($cfg);
18+
if (!$cfg || json_last_error() !== JSON_ERROR_NONE) { exit_line('Failed to parse json config'); }
19+
20+
$dbsid = 0;
21+
$dbhost = $cfg->mysql->servers[$dbsid]->hostname;
22+
$dbport = $cfg->mysql->servers[$dbsid]->port;
23+
24+
$dbname = $cfg->mysql->database;
25+
$dbuser = $cfg->mysql->username;
26+
$dbpass = $cfg->mysql->password;
27+
28+
$dbchrset = $cfg->mysql->character_set;
29+
30+
$db = new PDO(sprintf('mysql:host=%s;port=%d;dbname=%s;charset=%s', $dbhost, $dbport, $dbname, $dbchrset), $dbuser, $dbpass);
31+
if (!$db) { exit_line('Failed to connect to database'); }
32+
33+
$rs = $db->query('SELECT * FROM `users` ORDER BY `id` ASC;');
34+
if (!$rs) { exit_line('Failed to query database'); }
35+
36+
$cols = array();
37+
for ($i = 0; $i < $rs->columnCount(); $i++)
38+
{
39+
$cols[] = $rs->getColumnMeta($i)['name'];
40+
}
41+
fputcsv($csv, $cols);
42+
43+
while ($row = $rs->fetch(PDO::FETCH_NUM)) {
44+
fputcsv($csv, $row);
45+
}
46+
47+
fclose($csv);
48+
exit(0);

0 commit comments

Comments
 (0)