diff pdo.php @ 0:d7ab68b71c74

Initial commit
author Ivo Smits <Ivo@UCIS.nl>
date Mon, 11 Apr 2011 22:44:47 +0200
parents
children 005339a1b2ce
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pdo.php	Mon Apr 11 22:44:47 2011 +0200
@@ -0,0 +1,88 @@
+<?php
+class PDOWrapper {
+	private $numQueries = 0;
+	private $pdo = NULL;
+	
+	public static function connectMysql($host, $database, $user = NULL, $pass = NULL, $initialcommand = NULL) {
+		$options = array();
+		if ($initialcommand !== NULL) $options[PDO::MYSQL_ATTR_INIT_COMMAND] = $initialcommand;
+		return new self('mysql:dbname='.$database.';host='.$host, $user, $pass, $options);
+		//"SET NAMES utf8,time_zone = '+0:00'"
+	}
+	
+	public function __construct($dsn, $user = NULL, $pass = NULL, $options = NULL) {
+		try {
+			$this->pdo = new PDO($dsn, $user, $pass, $options);
+		} catch (PDOException $e) {
+			throw new Exception('Could not connect to database: '.$e->getMessage());
+		}
+		$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
+	}
+	public function __call($name, $arguments) {
+		if ($name == 'eval') {
+			$q = array_shift($arguments);
+			return $this->evalField($q, $arguments);
+		}
+	}
+	
+	private function queryi($query, $args = NULL) {
+		$this->numQueries++;
+		if ($args === NULL) {
+			//$stmt = $db_pdo->query($query);
+			$stmt = $this->pdo->prepare($query);
+			$stmt->execute();
+		} else {
+			if (!is_array($args)) $args = array($args);
+			$stmt = $this->pdo->prepare($query);
+			$stmt->execute($args);
+		}
+		return $stmt;
+	}
+	function insert($query, $args = NULL) {
+		$this->queryi($query, $args)->closeCursor();
+		return $this->pdo->lastInsertId();
+	}
+	function update($query, $args = NULL) {
+		global $db_pdo;
+		$stmt = $this->queryi($query, $args);
+		$cnt = $stmt->rowCount();
+		$stmt->closeCursor();
+		return $cnt;
+	}
+	function evalField($query, $args = NULL) {
+		$stmt = $this->queryi($query, $args);
+		$ret = $stmt->fetchColumn();
+		$stmt->closeCursor();
+		return $ret;
+	}
+	function evalRow($query, $args = NULL) {
+		$stmt = $this->queryi($query, $args);
+		$ret = $stmt->fetch(PDO::FETCH_NUM);
+		$stmt->closeCursor();
+		return $ret;
+	}
+	function evalRowAssoc($query, $args = NULL) {
+		$stmt = $this->queryi($query, $args);
+		$ret = $stmt->fetch(PDO::FETCH_ASSOC);
+		$stmt->closeCursor();
+		return $ret;
+	}
+	function evalAllAssoc($query, $args = NULL) {
+		$stmt = $this->queryi($query, $args);
+		$ret = $stmt->fetchAll(PDO::FETCH_ASSOC);
+		$stmt->closeCursor();
+		return $ret;
+	}
+	function evalAllKVP($query, $args = NULL) {
+		$stmt = $this->queryi($query, $args);
+		$ret = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
+		$stmt->closeCursor();
+		return $ret;
+	}
+	function evalColumn($query, $args = NULL) {
+		$stmt = $this->queryi($query, $args);
+		$ret = $stmt->fetchAll(PDO::FETCH_COLUMN);
+		$stmt->closeCursor();
+		return $ret;
+	}
+}