-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.php
More file actions
58 lines (47 loc) · 1.8 KB
/
db.php
File metadata and controls
58 lines (47 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
function dbConnect()
{
// TODO: Read this information from external file. Placed in special directory?
$dbh = new PDO('pgsql:user=db-man-public password=thisisaHorseBatteryStaple dbname=cmerc-db');
if (!$dbh)
{
die( "{'error':'Database unreachable'}" );
}
return $dbh;
}
// Based on code from: http://www.bin-co.com/php/scripts/sql2json/
// Function will take a PDO executed statement as argument and format the
// resulting data as a JSON (JavaScript Object Notation) string and return it.
function sql2json( $sql )
{
$json_str = "";
//See if there is anything in the query
if( $total = $sql->rowCount() )
{
$json_str .= "[\n";
$row_count = 0;
while( $data = $sql->fetch(PDO::FETCH_ASSOC) )
{
if ( count($data) > 1 ) { $json_str .= "{\n"; }
$count = 0;
foreach($data as $key => $value)
{
//If it is an associative array we want it in the format of "key":"value"
if( count($data) > 1) { $json_str .= "\"$key\":\"$value\""; }
else { $json_str .= "\"$value\""; }
//Make sure that the last item don't have a ',' (comma)
$count++;
if ( $count < count($data) ) { $json_str .= ",\n"; }
}
$row_count++;
if ( count($data) > 1 ) { $json_str .= "}\n"; }
//Make sure that the last item don't have a ',' (comma)
if($row_count < $total) { $json_str .= ",\n"; }
}
$json_str .= "]\n";
}
//Replace the '\n's - make it faster - but at the price of bad redability.
$json_str = str_replace("\n","",$json_str); //Comment this out when you are debugging the script
//Finally, output the data
return $json_str;
}