comparison pdo.php @ 0:d7ab68b71c74

Initial commit
author Ivo Smits <Ivo@UCIS.nl>
date Mon, 11 Apr 2011 22:44:47 +0200
parents
children 005339a1b2ce
comparison
equal deleted inserted replaced
-1:000000000000 0:d7ab68b71c74
1 <?php
2 class PDOWrapper {
3 private $numQueries = 0;
4 private $pdo = NULL;
5
6 public static function connectMysql($host, $database, $user = NULL, $pass = NULL, $initialcommand = NULL) {
7 $options = array();
8 if ($initialcommand !== NULL) $options[PDO::MYSQL_ATTR_INIT_COMMAND] = $initialcommand;
9 return new self('mysql:dbname='.$database.';host='.$host, $user, $pass, $options);
10 //"SET NAMES utf8,time_zone = '+0:00'"
11 }
12
13 public function __construct($dsn, $user = NULL, $pass = NULL, $options = NULL) {
14 try {
15 $this->pdo = new PDO($dsn, $user, $pass, $options);
16 } catch (PDOException $e) {
17 throw new Exception('Could not connect to database: '.$e->getMessage());
18 }
19 $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
20 }
21 public function __call($name, $arguments) {
22 if ($name == 'eval') {
23 $q = array_shift($arguments);
24 return $this->evalField($q, $arguments);
25 }
26 }
27
28 private function queryi($query, $args = NULL) {
29 $this->numQueries++;
30 if ($args === NULL) {
31 //$stmt = $db_pdo->query($query);
32 $stmt = $this->pdo->prepare($query);
33 $stmt->execute();
34 } else {
35 if (!is_array($args)) $args = array($args);
36 $stmt = $this->pdo->prepare($query);
37 $stmt->execute($args);
38 }
39 return $stmt;
40 }
41 function insert($query, $args = NULL) {
42 $this->queryi($query, $args)->closeCursor();
43 return $this->pdo->lastInsertId();
44 }
45 function update($query, $args = NULL) {
46 global $db_pdo;
47 $stmt = $this->queryi($query, $args);
48 $cnt = $stmt->rowCount();
49 $stmt->closeCursor();
50 return $cnt;
51 }
52 function evalField($query, $args = NULL) {
53 $stmt = $this->queryi($query, $args);
54 $ret = $stmt->fetchColumn();
55 $stmt->closeCursor();
56 return $ret;
57 }
58 function evalRow($query, $args = NULL) {
59 $stmt = $this->queryi($query, $args);
60 $ret = $stmt->fetch(PDO::FETCH_NUM);
61 $stmt->closeCursor();
62 return $ret;
63 }
64 function evalRowAssoc($query, $args = NULL) {
65 $stmt = $this->queryi($query, $args);
66 $ret = $stmt->fetch(PDO::FETCH_ASSOC);
67 $stmt->closeCursor();
68 return $ret;
69 }
70 function evalAllAssoc($query, $args = NULL) {
71 $stmt = $this->queryi($query, $args);
72 $ret = $stmt->fetchAll(PDO::FETCH_ASSOC);
73 $stmt->closeCursor();
74 return $ret;
75 }
76 function evalAllKVP($query, $args = NULL) {
77 $stmt = $this->queryi($query, $args);
78 $ret = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
79 $stmt->closeCursor();
80 return $ret;
81 }
82 function evalColumn($query, $args = NULL) {
83 $stmt = $this->queryi($query, $args);
84 $ret = $stmt->fetchAll(PDO::FETCH_COLUMN);
85 $stmt->closeCursor();
86 return $ret;
87 }
88 }