Location: PHPKode > projects > PHP Authentication using Uma > uma/Connection.class.php
<?
/**
 *
 * Database Connection Class
 *
 * Copyright (C) 2002 Vance Consulting LLC
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * is library is distributed in the hope that it will be useful,
 * t WITHOUT ANY WARRANTY; without even the implied warranty of
 * RCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * http://www.vanceconsulting.net/
 * hide@address.com
 *
 * Uma SourceForge Site: http://uma.sourceforge.net/
 *
 * Description:
 * Takes care of the database connection for a MySQL database.
*/

include_once("config.php");

/**
 * Connection puts a layer of abstraction between other classes and the
 * PHP database calls. The additional layer can allow you to implement 
 * this same class and method calls on basically any data source. 
 * Other datasources could be PostgreSQL, Oracle or XML. At least
 * that is the goal of this class. It only supports MySQL at this time.
 *
 * @package Uma
 * @author Keith Vance <hide@address.com>
 * @copyright 2002 Vance Consulting LLC
 * @link <a href="http://www.vanceconsulting.net/">www.vanceconsulting.net</a>
 */
class Connection {
    /**  Enable or disable debugging @var boolean **/
    var $_debug;
    /**  Enable or disable logging @var boolean **/
    var $_log;
    /**  File handle to log file @var filehandle **/
    var $_logfile;
    /** Name of data source host @var String **/
    var $_dbhost;
    /**  Name of data source @var String **/
    var $_database;
    /** Name to connect to data source @var String **/
    var $_dbuser;
    /** Password to connection to data source @var String **/
    var $_dbpassword;    
    /** The link to datasource. Currently call mysql_connect() @var ResultSet **/
    var $_link;  	    
    /** Result resource to the most recent query. @var Result **/
    var $_result;
    /** Current record of data @var Array**/
    var $_record;
    /** Current row of data @var Array **/
    var $_row;
    /** Number of affected rows affected by the last query @var int **/
    var $_affected_rows; 
    /** Name of table columns @var Array **/
    var $_fieldName;
    /** Number of colums or fields in a table @var int **/
    var $_numField;
    /** Number of rows returned from query @var int **/
    var $_rows;
    /** Error message from last query @var String **/
    var $_error;
    /** Error number from last query @var int **/
    var $_errornumber;
    /** ID of last record inserted @var int **/
    var $_insertId;
    /** 
      * Number of times nextRecord is called. Don't remember the
      * point of this one. I believe I use this internally for something.
      * @var int 
      **/
    var $_nextRecCounter = 0;
    
    /**
     * Connection Constructor.
     * Sets up and logging or debugging and calls $this->connect()
     *
     * @author Keith Vance (hide@address.com)
     */
    function Connection() {
	$this->_debug = DEBUG;
	if ($this->_debug) ini_set("display_errors", 1);
	$this->_log = LOG;

	if ($this->_log) {
	    ini_set("log_errors", 1);
	}

	$this->connect();
    }
	
    /**
     * Checks if connection is live. 
     *
     * @author Keith Vance <hide@address.com>
     * @return resource link on SUCCESS else FALSE
     */
    function live() {
	return $this->_link;
    }
    
    /**
     * Connect to mysql database.
     *
     * @author Keith Vance <hide@address.com> (November 4, 2000)
     */
    function connect () {
	$this->_link = @mysql_connect($this->_dbhost, $this->_dbuser, 
				     $this->_dbpassword);

	if (mysql_error()) {
	    error_log("<--Database Parameters-->\n".
		  "Host: " . $this->_dbhost . "\n".
		  "User: " . $this->_dbuser . "\n".
		  "Password: " . ($this->_dbpassword ? "Yes\n" : "No\n"));

	    if (!$this->_debug) {
		error_log(date("M D Y h:i:s") . "\nFailed to connect to ".
		      "database\n" . mysql_error() . "\n", 
			  1, ERROR_MESSAGE_RECPT);
		echo "<br><br><br><br><br><center>Please Wait...<br><br>".
		    "<META HTTP-EQUIV=Refresh ".
		    "CONTENT='10; URL=error.php'></center>\n";
		exit;
	    } else {
		error_log(mysql_error() . "\n", 0);
	    }
	}
	mysql_select_db($this->_database);
    }
	
    /**
     * Perform database query.
     *
     * @author Keith Vance <hide@address.com> (November 4, 2000)
     * @param String sql statement
     */
    function query ($queryString) {
	$this->_error = FALSE;
	$this->_errornumber = -999;
	$this->_record = false;	// reset this record
	$this->_result = @mysql_query($queryString, $this->_link);
	$this->_row = 0;
	$this->_error = @mysql_error($this->_link);
	$this->_errornumber = @mysql_errno($this->_link);
	if ($this->_error) {
	    if (!$this->_debug) {
		error_log(date("M D Y h:i:s")."\nQuery failed\n$queryString\n".
		      mysql_error() . "\n", 1, ERROR_MESSAGE_RECPT);
		echo "<br><br><br><br><br><center>Please Wait...<br><br>".
		    "<img src='/images/wait.gif'><META HTTP-EQUIV=Refresh ".
		    "CONTENT='10; URL=error.php'></center>\n";
		exit;
	    }

	    if ($this->_log) error_log(mysql_error() . "\n", 0);
	}

	return $this->_result;
    }
	
    /**
     * Shorthand for $this->query, it just calls $this->query.
     *
     * @param String SQL statement
     * @author Keith Vance <hide@address.com>
     */
    function q($queryString) {
	return $this->query($queryString);
    }
	
    /**
     * Determines if the last query ran without an incident.
     *
     * @author Keith Vance <hide@address.com> 2/28/02
     * @return boolean
     */
    function isError() {
	if ($this->_error == 0) {
	    return false;
	} else {
	    return true;
	}
    }
    
    /**
     * Takes a hash and inserts it into table as a row of data.
     * The keys of the hash represent the columns and the values
     * obviously represent the data.
     *
     * This method is especially helpful when inserting data from 
     * forms and the forms are setup to put everything in hash with 
     * keys being the column names and the values being the values for 
     * the insert.
     * @author Keith Vance <hide@address.com>  (November 3, 2000)
     * @param hash $data Hash where the keys represent the column names and
     * the values represent the values being inserted into the table
     * @param string $table The name of the table to do the insert into
     */
    function insert ($data, $table) {
	// build insert string
	$insert = "insert into " . $table . " ";
	$count = 1;
	while (list($key, $value) = each($data)) {
	    if ($count != count($data)) {
		$col .= $key . ", ";
		$val .= "'" . $value . "' ,";
		$count++;
	    } else {
		$col .= $key . " ";
		$val .= "'" . $value . "' ";
		$count++;
	    }
	}
	
	$insert .= "(" . $_insertCol . ") values (" . $_insertVal . ")";
	$this->query($insert);
    }
	
    /**
     * Takes a hash and updates a row of data with the values.
     * 
     * @author Keith Vance <hide@address.com> (November 4, 2000)
     * @param hash $data The keys of the hash represent columns in a database
     * and the values represents the data being inserted. 
     * @param String $table Name of the table being updated
     * @param String [$where] Example "where id = 1", if you don't want to
     * update the entire table.
     */
    function update ($data, $table, $where = FALSE) {
	$update = "update $table set ";
	$count = 1;
	
	foreach ($data as $col=>$value) {
	    if ($count < count ($data)) {
		$update .= $col." = '$value', ";
		$count++;
	    } else {
		$update .= $col." = '$value' ";
		$count++;
	    }
	}
		
	$update .= $where;
	$this->query($update);
    }
	
    /**
     * Advances to the next record in the result set
     *
     * @author Keith Vance (November 4, 2000)
     * @returns boolean 
     */
    function next() {
	$this->_record = @mysql_fetch_array($this->_result);
	$this->_row   += 1;
	$this->_errno = mysql_errno();
	$this->_error = mysql_error();
		
	if (!is_array($this->_record)) {
	    @mysql_free_result($this->_result);
	    $this->_result = 0;
	}
	
	return $this->_record;
    } 
	
    /**
     * Count the number of records in the result set
     *
     * @author Keith Vance (November 4, 2000)
     * @return int
     */
    function numRows () {
	return mysql_num_rows($this->_result);
    }
	
    /**
     * Get the last insert id.
     * 
     * @author Keith Vance (November 4, 2000)
     * @return int
     */
    function insertId () {
	return mysql_insert_id($this->_link);
    }

    /**
     * Returns the number of rows affected by an insert or update
     *
     * @author Keith Vance (Novemeber 4, 2000)
     * @return int
     */
    function affectedRows () {
	return mysql_affected_rows ($this->_link);
    }

    /**
     * Returns the current row as an array
     * 
     * @author Keith Vance (April 3, 2002)
     * @return Array
     */
    function row() {
	return $this->_record;
    }
	
    /**
     * Closes the database connect
     * @author Keith Vance (November 4, 2000)
     */
    function close () {
	@mysql_close($this->dbLink);
    }
	
    /**
     * gather information on a specific table and return data as hash
     * where the keys are the columns names and the values are arrays which
     * keys are 'type' and 'flag' and the values are the type and flags 
     * for the column
     *
     * If $all is set to true
     * 		Example:
     *		$columndata[column_name]=>[type]=>"varchar"
     *					  [flag]=>"primarykey"
     *			   [column_name]=>]type]=>"timestamp"
     *					  [flag]=>"not null"	
     *
     * If $all is set to false
     *		Example:
     *			$cols[0]=>"firstcolumn"
     *			$cols[1]=>"lastname";
     *
     * @author Keith Vance (March 5, 2001)
     * @return Array on success else false
     */
    function getTableData($table, $all = false) {
	$ret = false;
	$cols = mysql_list_fields($this->_database, $table);
	$numColumns = mysql_num_fields($cols);
	for ($i = 0; $i < $numColumns; $i++) {
	    if ($all) {
		$ret[mysql_field_name($cols, $i)] = array(
					  "type"=>mysql_field_type($cols, $i), 
					  "flag"=>mysql_field_flags($cols, $i)
					  );
	    } else {
		$ret[$i] = mysql_field_name($cols, $i);	
	    }
	}
	return $ret;
    }

    function changeDSName($newName) {
	mysql_select_db($newName, $this->_link);
	$this->_database = $newName;
    }
}
?>
Return current item: PHP Authentication using Uma