Welcome, guest | Sign In | My Account | Store | Cart

This is a simple base class that extends PDO and provides some useful helper functions such as _getRows and _getAsRow()

PHP, 99 lines
 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php

class Foo extends PDO {
  /*
  * __constructor: create a new Foo object
  * @ param $cfg: usually a STDClass object with these properties
  * stdClass Object
  (
  [host] => localhost
  [db] => mysql
  [user] => username
  [pass] => password
  )
  */
  private $cfg;
  public $dsn;
  
  function __construct($cfg) {
    try {
      $this->dsn = "mysql:host=$cfg->host;dbname=$cfg->db";
      parent::__construct($this->dsn, $cfg->user, $cfg->pass);
      $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // throw exceptions
      $this->cfg = $cfg;
    }
    catch(Exception $e) {
      // XXX need to look for Array output on all ops
      print "Error: " . $e->getMessage();
    }
  }
  
  /* implement crazy code here */
  
  
  
  /* handy utility functions */
  
  function _getAsRow($sql, $i = 0) {
    try {
      $sth = $this->query($sql);
      $arr = $sth->fetchAll();
      $out = array();
      foreach($arr as $row) {
        $out[] = $row[$i];
      }
      return array(
        1,
        $out
      );
    }
    catch(Exception $e) {
      return $this->_err($e);
    }
  }
  // get all data returned by the query
  
  function _getRows($sql) {
    try {
      $sth = $this->query($sql);
      return array(
        1,
        $sth->fetchAll(PDO::FETCH_ASSOC)
      );
    }
    catch(Exception $e) {
      return $this->_err($e);
    }
  }
  /* run a query that doesn't return data, we want the affected rows instead */
  
  function boolQuery($sql) {
    try {
      $sth = $this->query($sql);
      return array(
        1,
        $sth->rowCount
      );
    }
    catch(Exception $e) {
      return $this->_err($e);
    }
  }
  /* return the expected error structure */
  private function _err($e) {
    return array(
      0,
      $e->getMessage()
    );
  }
  // dumper
  
  function _dump($data) { // pass in $_GET, etc
    $args = func_get_args();
    if (count($args) > 1) {
      return "\n<pre>\n" . print_r($args, 1) . "\n</pre>\n";
    } else {
      return "\n<pre>\n" . print_r($data, 1) . "\n</pre>\n";
    }
  }
}
Created by Jeff Griffiths on Mon, 25 Jun 2007 (MIT)
PHP recipes (51)
Jeff Griffiths's recipes (3)

Required Modules

  • (none specified)

Other Information and Tasks