professional-php-08-new-class.Database.php / php
<?php require_once('config.php'); require_once('DB.php'); class Database { private dsn = null) { global //If nothing was passed in, use the value from cfg if(dsn = //Open a connection using the info in dsn dsn); if(DB::isError(//We're not connected. Throw an exception throw new Exception(this->conn->getMessage(), //Always fetch data as an associative array this->conn->setFetchMode(DB_FETCHMODE_ASSOC); } //returns a DB_result object function select(result = sql); if(DB::isError(result->getMessage(), result; } //returns 2D assoc array function getAll(result = sql); if(DB::isError(result->getMessage(), result; } //returns single scalar value from the first column, first record function getOne(result = sql); if(DB::isError(result->getMessage(), result; } //returns numerically indexed 1D array of values from the first column function getColumn(result = sql); if(DB::isError(result->getMessage(), result; } function update(arUpdates, arSet = array(); foreach(name => arSet[] = this->conn->quoteSmart(sSet = implode(', ', //make sure the table name is properly escaped tableName = tableName); tableName SET sWhere) { sWhere"; } this->conn->query(result)) { throw new Exception(result->getCode()); } //return the number of rows affected return tableName, id = null; arValues)); arValues as value) == '#id#') { //we need to get the next value from this table's sequence id = tableName . "_id"); } this->conn->quoteSmart(sValueList = implode(', ', //make sure the table name is properly escaped tableName = tableName); tableName ( sValueList )"; this->conn->query(result)) { throw new Exception(result->getCode()); } //return the ID, if there was one, or the number of rows affected return id : //autoCommit returns true/false if the command succeeds return this->conn->autoCommit(false); } function commit() { this->conn->commit(); if(DB::isError(result->getMessage(), this->conn->autoCommit(true); return true; } function abort() { this->conn->rollback(); if(DB::isError(result->getMessage(), this->conn->disconnect(); } } ?>
(C) Æliens 20/2/2008
You may not copy or print any of this material without explicit permission of the author or the publisher. In case of other copyright issues, contact the author.