Login   Register  
PHP Classes
elePHPant
Icontem

File: Database.php

Recommend this page to a friend!
Stumble It! Stumble It! Bookmark in del.icio.us Bookmark in del.icio.us
  Classes of John Luxford  >  Database.php  >  Database.php  >  Download  
File: Database.php
Role: ???
Content type: text/plain
Description: The basic Database and Query class file.
Class: Database.php
Author: By
Last change:
Date: 2001-08-31 20:13
Size: 12,023 bytes
 

Contents

Class file image Download
<?php
//
// +----------------------------------------------------------------------+
// | Sitellite - Content Management System                                |
// +----------------------------------------------------------------------+
// | Copyright (c) 2001 Simian Systems                                    |
// +----------------------------------------------------------------------+
// | This software is released under the Simian Open Software License.    |
// | Please see the accompanying file OPENLICENSE for licensing details!  |
// |                                                                      |
// | You should have received a copy of the Simian Open Software License  |
// | along with this program; if not, write to Simian Systems,            |
// | 101-314 Broadway, Winnipeg, MB, R3C 0S7, CANADA.  The Simian         |
// | Public License is also available at the following web site           |
// | address: <http://www.simian.ca/license.php>                          |
// +----------------------------------------------------------------------+
// | Authors: John Luxford <lux@simian.ca>                                |
// +----------------------------------------------------------------------+
//
// Database is a database abstraction class; a unified means
// of accessing different relational database systems.
//

/*!

<package name="Database">

<class	name="Database"
			access="public"
			date="2001-05-16 23:21:00"
			version="1.0">

	<author	name="John Luxford"
				email="lux@simian.ca"
				url="http://www.simian.ca/" />

	<summary>Database is a database abstraction class; a unified means
of accessing different relational database systems.  It is accompanied
by a second class called Query, and relies on driver classes to provide
all the database specific functionality.</summary>

	<example>$db = new Database ("Driver:Host:Database", "Username", "Password", 1);

// create a database query object
$q = $db->query ("SELECT * FROM table");

if ($q->execute ()) {
	while ($row = $q->fetch ()) {
		// do something with the $row object
	}
	$q->free ();
} else {
	// query failed
}</example> !*/

class Database {
	/*! <property name="connection" access="public" type="resource">
	<summary>Contains the database connection resource.</summary>
	</property> !*/
	var $connection;

	/*! <property name="transactions" access="public" type="integer">
	<summary>Boolean value denoting whether to enable transactions in the
	current database.</summary>
	</property> !*/
	var $transactions = 0;

	/*! <property name="driver" access="public" type="string">
	<summary>Contains the name of the database driver being used.</summary>
	</property> !*/
	var $driver;

	/*! <property name="host" access="public" type="string">
	<summary>Contains the name of the database host.</summary>
	</property> !*/
	var $host;

	/*! <property name="name" access="public" type="string">
	<summary>Contains the name of the database being used.</summary>
	</property> !*/
	var $name;

	/*! <property name="user" access="public" type="string">
	<summary>Contains the username used to connect to the current database.</summary>
	</property> !*/
	var $user;

	/*! <property name="pass" access="public" type="string">
	<summary>Contains the password used to connect to the current database.</summary>
	</property> !*/
	var $pass;

	/*! <property name="dbd" access="private" type="object">
	<summary>Contains the loaded database driver.</summary>
	</property> !*/
	var $dbd;

	/*! <method name="Database" access="public">
	<summary>Constructor method.  Establishes a connection to the specified
	database system.

	$constr is the connection string that is used to tell Database
	how to find the database you are looking for.  It takes the
	format: "Driver:Hostname:Database".

	$user is the username required to connect to the database.

	$pass is the password required to connect to the database.

	$persistent is a 1 or 0 (true or false) value denoting whether
	to establish a persistent connection or not.  Default is 1 (true).</summary>
	<param name="constr" type="string" default="::" />
	<param name="user" type="string" />
	<param name="pass" type="string" />
	<param name="persistent" type="boolean" default="1" />
	</method> !*/
	function Database ($connstr = "::", $user = "", $pass = "", $persistent = 1) {
		if (ereg ("^([^:]+):([^:]*):(.+)$", $connstr, $regs)) {
			$this->driver = $regs[1];
			$this->host = $regs[2];
			$this->name = $regs[3];
		} else {
			return 0;
		}
		$this->user = $user;
		$this->pass = $pass;
		$this->persistent = $persistent;
		if (file_exists (getcwd () . '/inc/lib/' . $this->driver . "_Driver.php")) {
			include (getcwd () . '/inc/lib/' . $this->driver . "_Driver.php");
		} else {
			return 0;
		}
		$driver = $this->driver . "_Driver";
		$this->dbd = new $driver ($this->name, $this->host, $this->user, $this->pass, $this->persistent);
		$this->connection = $this->dbd->connection;
	}

	/*! <method name="query" access="public">
	<summary>Creates and returns a Query object.

	$sql is the SQL query you wish to execute with this object.</summary>
	<param name="sql" type="string" />
	<returns type="object" />
	</method> !*/
	function query ($sql = "") {
		$classname = $this->driver . "_Query";
		$q = new $classname ($sql, $this->connection);
		return $q;
		// $this->dbd->query ($sql, $this->connection);
	}
}

/*! </class> !*/

/*!

<class	name="Query"
			access="public"
			date="2001-05-16 23:21:00"
			version="1.0">

	<author	name="John Luxford"
				email="lux@simian.ca"
				url="http://www.simian.ca/" />

	<summary>Query is the counterpart class to Database.  It provides the framework
for querying a database.</summary>

	<example>$db = new Database ("Driver:Host:Database", "Username", "Password", 1);

// create a database query object
$q = $db->query ("SELECT * FROM table");

if ($q->execute ()) {
	while ($row = $q->fetch ()) {
		// do something with the $row object
	}
	$q->free ();
} else {
	// query failed
}</example> !*/

class Query {
	/*! <property name="sql" access="public" type="string">
	<summary>Contains the SQL query to be executed.</summary>
	</property> !*/
	var $sql = "";

	/*! <property name="result" access="public" type="resource">
	<summary>Contains the result identifier for the current execution.</summary>
	</property> !*/
	var $result = "";

	/*! <property name="field" access="public" type="string">
	<summary>Currently unused.</summary>
	</property> !*/
	var $field = "";

	/*! <property name="connection" access="public" type="resource">
	<summary>Contains a local copy of the database connection resource.</summary>
	</property> !*/
	var $connection = "";

	/*! <method name="Query" access="public">
	<summary>Constructor method.

	$sql is the SQL query you wish to execute with this object.</summary>
	<param name="sql" type="string" />
	</method> !*/
	function Query ($sql = "", $connection = "") {
		$this->sql = $sql;
		$this->connection = $connection;
	}

	/*! <method name="bind_values" access="private">
	<summary>Replaces any occurrences of ?? in $sql with the proper value from
	$values.  Called automatically just prior to executing the current query.

	$values is an array of values to substitute.

	Returns the new SQL query.  Note: does not modify the actual $sql property.</summary>
	<param name="values" type="array" />
	<returns type="string" />
	</method> !*/
	function bind_values ($values) {
		// accepts bind values using the '??' notation

		// turn ??'s that are inside quotes into =Q=Q to make binding easier
		// $working_sql = preg_replace ('/\'(.*?)\?\?(.*?[^\\])\'/', "'\\1=Q=Q\\2'", $this->sql);
		// $working_sql = preg_replace ('/"(.*?)\?\?(.*?[^\\])"/', "\"\\1=Q=Q\\2\"", $working_sql);

		// echo "<pre>$working_sql</pre>";
		$working_sql = $this->sql;

		if (is_array ($values[0])) {
			$values = $values[0];
		}

		if (ereg ("(\\?\\?)", $working_sql)) {
			$count = count ($values);
			$sql = split ("\\?\\?", $working_sql);
			if (count ($sql) == ($count + 1)) {
				// replace all bind markers
				for ($i = 0; $i < (count ($sql) - 1); $i++) {
					$sql[$i] .= "'" . $values[$i] . "'";
				}
				$this->tmp_sql = join ("", $sql);
				// turn =Q=Q back into ?? now
				// $this->tmp_sql = str_replace ("=Q=Q", "??", $this->tmp_sql);
			} else {
				// wrong number of bind values
				$this->result = 0;
				return $this->result;
			}
		} else {
			$this->tmp_sql = $this->sql;
		}
		//echo "<pre>$this->tmp_sql</pre>";
		//echo join (":", $values);
	}

	/*! <method name="execute" access="public">
	<summary>Executes the current SQL query.

	$values is an array of values to substitute.

	Returns the new SQL query.  Note: does not modify the actual $sql property.</summary>
	<param name="values" type="array" />
	<returns type="resource" />
	</method> !*/
	function execute () {}			// executes the sql query

	/*! <method name="field" access="public">
	<summary>Returns the name of the specified column in the table currently being queried.

	$num is the column number.  Note: Some database systems begin with
	column 0, while others with 1.</summary>
	<param name="num" type="integer" />
	<returns type="string" />
	</method> !*/
	function field ($num = 0) {}	// returns a column name when given a number

	/*! <method name="rows" access="public">
	<summary>Returns the number of rows affected or found by the current query.</summary>
	<returns type="integer" />
	</method> !*/
	function rows () {}				// returns the number of rows affected or found

	/*! <method name="lastid" access="public">
	<summary>Returns the row ID generated by the database during the previous
	SQL insert query.</summary>
	<returns type="integer" />
	</method> !*/
	function lastid () {}			// returns the last autonum from an insert

	/*! <method name="fetch" access="public">
	<summary>Returns the next row of data from the current query, always in the
	form of an object, with each column as its properties.</summary>
	<returns type="object" />
	</method> !*/
	function fetch () {}				// returns the next row

	/*! <method name="free" access="public">
	<summary>Tells the database system to let go of its data from the previous
	query.</summary>
	</method> !*/
	function free () {}				// frees the query
}

/*! </class>

</package>

 !*/


/* test code for MySQL driver...
$db = new Database ("MySQL:localhost:go", "lux", "SimianSystemsCA");
echo 'MySQL Connection : ' . $db->connection . '<br /><br />';

$q = $db->query ("select * from news where date = ?? and body = 'asdf??asdf'");
if ($q->execute ('2001-07-22')) {
	echo "Results found: " . $q->rows () . '<br />';
	while ($tbl = $q->fetch ()) {
		echo 'Name: ' . $tbl->{$q->field (1)} . '<br />';
	}
	$q->free ();
} else {
	echo "failed.";
}

echo '<br /><br />'; */

/* test code for ODBC driver...
$db = new Database ("ODBC::sitellite_dev", "lux", "SimianSystemsCA", 0);
echo 'ODBC Connection : ' . $db->connection . '<br /><br />';

$q = $db->query ("select * from test where age >= ??");
if ($q->execute (18)) {
	echo "Results found: " . $q->rows () . '<br />';
	while ($tbl = $q->fetch ()) {
		echo 'Name: ' . $tbl->{$q->field (1)} . '<br />';
	}
	$q->free ();
} else {
	echo "failed.";
}

echo '<br /><br />'; */

/* test code for IBase driver...
$db = new Database ("IBase::I:\sitellite\interbase_port\sitellite_dev.gdb", "sysdba", "SimianSystemsCA");
echo 'IBase Connection : ' . $db->connection . '<br /><br />';

$q = $db->query ('SELECT * FROM TEST WHERE AGE >= 18 ;');
if ($q->execute ()) {
	echo "Results found: " . $q->rows () . '<br />';
	while ($tbl = $q->fetch ()) {
		echo 'Name: ' . $tbl->{$q->field (1)} . '<br />';
	}
	$q->free ();
} else {
	echo "failed.";
} */

?>