Open-Source PHP Framework - Designed for rapid development of performance-oriented scalable applications

/sql/postgresql

[return to app]
1 <?php
2
/**
3  * Converts the procedural PostgreSQL PHP class to object-oriented
4  */
5
class postgresql {
6     
/**
7      * Database link ID
8      * @var object
9      */
10     
public $linkid;
11
12     
/**
13      * The database method used to sanitize user input strings
14      */
15     
const ESCAPE_STRING 'escape_string';
16
17     
/**
18      * Query results object
19      * @var object
20      */
21     
protected $_result;
22
23     
/**
24      * Connect to PostgreSQL
25      *
26      * @param string $host
27      * @param string $username
28      * @param string $passwd
29      * @param string $dbname
30      */
31     
public function __construct($host$username$password$dbname$connectType null) {
32         try {
33             
$this->linkid pg_connect("host=$host dbname=$dbname user=$username password=$password",
 
$connectType);
34             if (!
$this->linkid) {
35                 throw new 
Exception('Cannot connect to PostgreSQL');
36             }
37         } catch (
Exception $e) {
38             
$this->error $e->getMessage();
39         }
40     }
41
42     
/**
43      * Query the database
44      *
45      * @param string $query
46      * @return object
47      */
48     
public function query($query){
49         try{
50             
$this->_result pg_query($this->linkid$query);
51             if(!
$this->_result) {
52                 throw new 
Exception('Query failed: ' $query);
53             }
54         } catch (
Exception $e){
55             
$this->error $e->getMessage();
56         }
57        return 
$this->_result;
58     }
59
60     
/**
61      * Catch-all method to handle the different PostgreSQL functions allowing you to call:
62      *
63      * fetchAllColumns()
64      * fetchAll()
65      * fetchArray()
66      * fetchAssoc()
67      * fetchObject()
68      * fetchResult()
69      * fetchRow()
70      *
71      * Note: passing the result set to fetch functions is optional as a convenience
72      *
73      * @param string $name
74      * @param mixed $val
75      */
76     
public function __call($name$val) {
77         if (!
$val) {
78             
$fetch explode('fetch'$name);
79             if (
$fetch && isset($fetch[1])) {
80                 
$fetchName 'pg_fetch_' strtolower($fetch[1]);
81                 if (
$fetchName == 'pg_fetch_allcolumns') {
82                     
$fetchName 'pg_fetch_all_columns';
83                 }
84                 return 
$fetchName($this->_result);
85             }
86         }
87         
$name strtolower('pg_' preg_replace('/[A-Z]/''_$0'$name));
88         if (
function_exists($name)) {
89             return 
call_user_func_array($name$val);
90         }
91     }
92 }