Location: PHPKode > scripts > xMySQL > xmysql/xmysql.class.php
<?php
// xMySQL 2.1
// Copyright (c) 2002, 2003 by Alexander Serbe. All rights reserved.
// ---------------------------------------------------------------------------------
// Version:        2.1
// Date:           16 May 2003
// ---------------------------------------------------------------------------------
// Author:         Alexander Serbe (hide@address.com)
// Contributor(s): 
// ---------------------------------------------------------------------------------
// Requirements:   PHP4 (>=4.1), MySQL (>=3.23)
// ---------------------------------------------------------------------------------
// License:        GNU General Public License (http://www.gnu.org/licenses/gpl.html)
// ---------------------------------------------------------------------------------
// This program is free software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the Free Software
// Foundation; either version 2 of the License, or (at your option) any later
// version.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
// PARTICULAR PURPOSE.  See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this
// program; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
// Suite 330, Boston, MA  02111-1307  USA.
// ---------------------------------------------------------------------------------
// Dieses Programm ist freie Software. Sie können es unter den Bedingungen der GNU
// General Public License, wie von der Free Software Foundation veröffentlicht,
// weitergeben und/oder modifizieren, entweder gemäß Version 2 der Lizenz oder (nach
// Ihrer Option) jeder späteren Version. 
// Die Veröffentlichung dieses Programms erfolgt in der Hoffnung, daß es Ihnen von
// Nutzen sein wird, aber OHNE IRGENDEINE GARANTIE, sogar ohne die implizite Garantie
// der MARKTREIFE oder der VERWENDBARKEIT FÜR EINEN BESTIMMTEN ZWECK. Details finden
// Sie in der GNU General Public License. 
// Sie sollten eine Kopie der GNU General Public License zusammen mit diesem Programm
// erhalten haben. Falls nicht, schreiben Sie an die Free Software Foundation, Inc.,
// 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
// ---------------------------------------------------------------------------------
// Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les
// termes de la Licence Publique Générale GNU publiée par la Free Software
// Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
// Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE,
// ni explicite ni implicite, y compris les garanties de commercialisation ou
// d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale
// GNU pour plus de détails. 
// Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps
// que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
// ---------------------------------------------------------------------------------

class xMySQL
{
	// Initialize object variables -------------------------------------------------
	var $conn_id;					// Mixed [int/bool]. MySQL connection id.
	var $db_host;					// String. MySQL host name.
	var $db_name;					// String. Database name.
	var $db_pwd;					// String. MySQL password.
	var $db_uid;					// String. MySQL user name.
	var $host_list;					// String. Contents of the host list file.
	var $os;						// Object. objectStatus instance (reference).
	var $q_result;					// Integer. MySQL resource id.
	
	// xMySQL ----------------------------------------------------------------------
	// Signature: void xMySQL ( string host_list, integer host_id [, object os] )
	// Access: Public (Constructor)
	// Initializes a new xMySQL object. Returns void.
	function xMySQL ( $host_list, $host_id, $os="" )
	{
		// Initialize class variables
		$this->conn_id = 0;
		$this->os = false;
		$this->host_list = false;
		$this->q_result = 0;
		
		if ( is_object ( $os ) )
		{
			$this->os = $os;
			$this->os->statusMessage ( "xMySQL", "", "Object initialized.", 1 );
		}
		
		$this->host_list = $this->loadFile ( $host_list );
		
		if ( $this->host_list )
		{
			$this->host_list = str_replace ( "<?php", "", $this->host_list );
			$this->host_list = str_replace ( "?>", "", $this->host_list );
		}
				
		$this->setDbConnection ( $host_id );
	} // xMySQL -------------------------------------------------------------- end -
	
	// classInfo -------------------------------------------------------------------
	// Signature: array classInfo ( void )
	// Access: Public
	// Provides information about the class you're using. Returns an associative
	// array containing the following elements: name, version, extends, implements,
	// date, author, email, contributors, copyright, license, download (url),
	// check_version (url).
	function classInfo ()
	{
		$class_info = array (
			'name' => 'xMySQL',
			'version' => '2.1',
			'extends' => '',
			'implements' => 'objectStatus (>=0.2)',
			'date' => '16 Mey 2003',
			'author' => 'Alexander Serbe',
			'email' => 'hide@address.com',
			'contributors' => '',
			'copyright' => '2003 by Alexander Serbe. All rights reserved.',
			'license' => 'GNU General Public License',
			'category' => 'Databases;MySQL',
			'download' => '',
			'check_version' => ''
		);
		
		return $class_info;
	}
	
	// loadFile --------------------------------------------------------------------
	// Signature: mixed [str/array/bool] loadFile ( string file [, integer mode] )
	// Access: Private
	// Loads the contents of a file either into a scalar variable (mode 1) or an
	// array (mode 2). Returns the file content in the chosen format or false if
	// the file was empty or not found.
	function loadFile ( $file, $mode=1 )
	{
		if ( file_exists ( $file ) )
		{
			$file_empty = true;
			( $mode == 1 ) ? $content = "" : $content = array();
			
			$fp = fopen ( $file, "r" );
			if ( $mode == 1 )
			{ // Store file content in a scalar
				$content = fread ( $fp, filesize ( $file ) );
				( strlen ( $content ) > 0 ) ? $file_empty = false : 0;
			}
			else
			{ // Store file content in an array
				while ( !feof ( $fp ) )
					$content[] = fgets ( $fp );
				( count ( $content ) > 0 ) ? $file_empty = false : 0; 
			}
			
			if ( !$file_empty )
			{
				( $this->os ) ? $this->os->statusMessage ( "xMySQL", "loadFile", "Executed. File '$file' loaded (mode $mode).", 1 ) : 0;
				return $content;
			}
			else
			{
				( $this->os ) ? $this->os->statusMessage ( "xMySQL", "loadFile", "File '$file' was empty.", 2 ) : 0;
				return false;
			}
		}
		else
		{
			( $this->os ) ? $this->os->statusMessage ( "xMySQL", "loadFile", "File $file does not exist.", 2 ) : 0;
			return false;
		} 
	} // loadFile ------------------------------------------------------------ end -
	
	// setDbConnection -------------------------------------------------------------
	// Signature: boolean setDbConnection ( integer host_id )
	// Access: Public
	// Stores the data needed to connect to a mysql server in the list. Returns true
	// if the host was found in the list, otherwise false.
	function setDbConnection ( $host_id )
	{
		$mysql_host = "";
		
		eval ( $this->host_list );
		
		if ( is_array ( $mysql_host ) )
		{
			if ( count ( $mysql_host[$host_id] ) > 0 )
			{
				$this->db_host = $mysql_host[$host_id]['host'];
				$this->db_uid  = $mysql_host[$host_id]['uid'];
				$this->db_pwd  = $mysql_host[$host_id]['pwd'];
				$this->db_name = $mysql_host[$host_id]['db'];
				
				( $this->os ) ? $this->os->statusMessage ( "xMySQL", "setDbConnection", "Executed. Host '" . $this->db_host . "', user '" . $this->db_uid . "'.", 1 ) : 0;
				return true;
			}
			else
			{
				( $this->os ) ? $this->os->statusMessage ( "xMySQL", "setDbConnection", "Can't find host $host_id.", 2 ) : 0;
				return false;
			}
		}
		else
		{
			( $this->os ) ? $this->os->statusMessage ( "xMySQL", "setDbConnection", "Host list is not an array.", 2 ) : 0;
			return false;
		}
	} // setDbConnection ----------------------------------------------------- end -
	
	// xClose ----------------------------------------------------------------------
	// Signature: boolean xClose ( void )
	// Access: Private
	// Disconnects from a MySQL server. Returns true if the attempt was successful,
	// otherwise false.
	function xClose ()
	{
		if ( $this->q_result )
		{
			@mysql_free_result ( $this->q_result );
			$this->q_result = 0;
		}
		
		if ( @mysql_close () )
		{
			$this->conn_id = 0;
			( $this->os ) ? $this->os->statusMessage ( "xMySQL", "xClose", "Connection terminated.", 1 ) : 0;
			return true;
		}
		else
		{
			( $this->os ) ? $this->os->statusMessage ( "xMySQL", "xClose", "Could not terminate connection. MySQL said: " . mysql_error () . ".", 2, mysql_errno () ) : 0;
			return false;
		}
	} // xClose -------------------------------------------------------------- end -
	
	// xConnect --------------------------------------------------------------------
	// Signature: boolean xConnect ( void )
	// Access: Private
	// Connects to a MySQL server. Returns true if the attempt was successful,
	// otherwise false.
	function xConnect ()
	{
		if ( $this->conn_id = @mysql_connect ( $this->db_host, $this->db_uid, $this->db_pwd ) )
		{
			if ( @mysql_select_db ( $this->db_name, $this->conn_id ) )
			{
				( $this->os ) ? $this->os->statusMessage ( "xMySQL", "xConnect", "Connected to host " . $this->db_host . ", database " . $this->db_name . " selected.", 1 ) : 0;
				return true;
			}
			else
			{
				( $this->os ) ? $this->os->statusMessage ( "xMySQL", "xConnect", "Executed. Conntected to host " . $this->db_host . ". Could not select database " . $this->db_name . ". MySQL said: " . mysql_error () . ".", 2, mysql_errno () ) : 0;
				mysql_close ();
				return false;
			}
		}
		else
		{
			( $this->os ) ? $this->os->statusMessage ( "xMySQL", "xConnect", "Could not connect to host " . $this->db_host . ". MySQL said: " . mysql_error () . ".", 2, mysql_errno () ) : 0;
			return false;
		}
	} // xConnect ------------------------------------------------------------ end -
	
	// xDelete ---------------------------------------------------------------------
	// Signature: integer xDelete ( string table [, string where] )
	// Access: Public
	// Deletes one or several records from a table. Returns the number of deleted
	// records, if no records were deleted false.
	function xDelete ( $table, $where="" )
	{
		$q = "DELETE FROM $table";
		( $where ) ? $q .= " WHERE $where" : 0;
		
		if ( $this->xConnect () )
		{
			if ( @mysql_query ( $q, $this->conn_id ) )
			{
				$cnt = @mysql_affected_rows ( $this->conn_id );
				
				if ( !$where )
					$msg = "All records deleted.";
				else
					$msg = "$cnt record(s) deleted.";
				
				( $this->os ) ? $this->os->statusMessage ( "xMySQL", "xDelete", "Executed. $msg", 1 ) : 0;
				$this->xClose ();
				return $cnt;
			}
			else
			{
				( $this->os ) ? $this->os->statusMessage ( "xMySQL", "xDelete", "Could not execute query '$q'. MySQL said: " . mysql_error () . ".", 2, mysql_errno () ) : 0;
				$this->xClose ();
				return false;
			}
		}
		else
		{
			( $this->os ) ? $this->os->statusMessage ( "xMySQL", "xDelete", "Failed connecting to MySQL host.", 2 ) : 0;
			return false;
		}
	} // xDelete ------------------------------------------------------------- end -
	
	// xInsert ---------------------------------------------------------------------
	// Signature: integer xInsert ( string table, array fields, array values )
	// Access: Public
	// Inserts a record into a table. Returns the id of the inserted record. If
	// an error occured false.
	function xInsert ( $table, $fields, $values )
	{
		if ( ( count ( $fields ) > 0 ) && count ( $fields ) != count ( $values ) )
		{
			( $this->os ) ? $this->os->statusMessage ( "xMySQL", "xInsert", "Field count does not match value count. Executeion aborted.", 2 ) : 0;
			return false;
		}
		
		$q = "INSERT INTO $table ";
		if ( count ( $fields ) > 0 )
		{
			$q .= "(";
			for ( $i=0; $i<count ( $fields ); $i++ )
			{
				$q .= $fields[$i];
				( $i < ( count ( $fields ) - 1 ) ) ? $q .= ", " : 0;
			}
			$q .= ")";
		}
		$q .= "VALUES ( ";
		for ( $i=0; $i<count ( $values ); $i++ )
		{
			( $values[$i] != "now()" && $values[$i] != "NULL" ) ? $q .= "'" . $values[$i] . "'" : $q .= $values[$i];
			( $i < ( count ( $values ) - 1 ) ) ? $q .= ", " : 0;
		}
		$q .= ")";
		
		if ( $this->xConnect () )
		{
			if ( @mysql_query ( $q, $this->conn_id ) )
			{
				$x = @mysql_insert_id ();
				( $this->os ) ? $this->os->statusMessage ( "xMySQL", "xInsert", "Executed.", 1 ) : 0;
				$this->xClose ();
				return $x;
			}
			else
			{
				( $this->os ) ? $this->os->statusMessage ( "xMySQL", "xInsert", "Failed executing query '$q'. MySQL said: " . mysql_error () . ".", 2, mysql_errno () ) : 0;
				$this->xClose ();
				return false;
			}
		}
		else
		{
			( $this->os ) ? $this->os->statusMessage ( "xMySQL", "xInsert", "Failed connecting to MySQL host.", 2 ) : 0;
			return false;
		}
	} // xInsert ------------------------------------------------------------- end -
	
	// xQuery ----------------------------------------------------------------------
	// Signature: integer xQuery ( string query )
	// Access: Public
	// Executes a query and returns the resource locator id. If an error occured,
	// xQuery returns false.
	function xQuery ( $query )
	{
		if ( $this->xConnect () )
		{
			if ( $x = @mysql_query ( $query, $this->conn_id ) )
			{
				( $this->os ) ? $this->os->statusMessage ( "xMySQL", "xQuery", "Executed.", 1 ) : 0;
				$this->xClose ();
				return $x;
			}
			else
			{
				( $this->os ) ? $this->os->statusMessage ( "xMySQL", "xQuery", "Failed executing query '$q'. MySQL said: " . mysql_error () . ".", 2, mysql_errno () ) : 0;
				$this->xClose ();
				return false;
			}
		}
		else
		{
			( $this->os ) ? $this->os->statusMessage ( "xMySQL", "xQuery", "Failed connecting to MySQL host.", 2 ) : 0;
			return false;
		}
	} // xQuery -------------------------------------------------------------- end -
	
	// xSelect ---------------------------------------------------------------------
	// Signature: array xSelect ( string select, string from [, string where [,
	// string order_by [, string limit]]] )
	// Access: Public
	// Executes a select query and returns a two-dimensional array containing the
	// results. If no records were found xSelect returns false.
	function xSelect ( $select, $from, $where="", $order_by="", $limit="" )
	{
		$result = "";
		
		$q = "SELECT $select FROM $from ";
		( $where ) ? $q .= "WHERE $where " : 0;
		( $order_by ) ? $q .= "ORDER BY $order_by " : 0;
		( $limit ) ? $q .= "LIMIT $limit" : 0;
		
		if ( $this->xConnect () )
		{
			if ( $this->q_result = @mysql_query ( $q, $this->conn_id ) )
			{
				$num = 0;
				while ( $row = @mysql_fetch_row ( $this->q_result ) )
				{
					for ( $i=0; $i<count ( $row ); $i++ )
						$result[$num][$i] = $row[$i];
					$num++;
				}
				
				if ( count ( $result )  > 0 )
				{
					$msg = "Executed. " . count ( $result ) . " record(s) found.";
				}
				else
				{
					$msg = "Executed. No records found.";
				}
				( $this->os ) ? $this->os->statusMessage ( "xMySQL", "xSelect", "$msg", 1 ) : 0;
				$this->xClose ();
				return $result;
			}
			else
			{
				( $this->os ) ? $this->os->statusMessage ( "xMySQL", "xSelect", "Failed executing query '$q'. MySQL said: " . mysql_error () . ".", 2, mysql_errno () ) : 0;
				$this->xClose ();
				return false;
			}
		}
		else
		{
			( $this->os ) ? $this->os->statusMessage ( "xMySQL", "xSelect", "Failed connecting to MySQL host.", 2 ) : 0;
			return false;
		}
	} // xSelect ------------------------------------------------------------- end -
	
	// xUpdate ---------------------------------------------------------------------
	// Signature: integer xUpdate ( string table, array fields, array values [,
	// string where] )
	// Access: Public
	// Executes an update query. Returns the number of affected rows or false.
	function xUpdate ( $table, $fields, $values, $where="" )
	{
		if ( count ( $fields ) != count ( $values ) )
		{
			( $this->os ) ? $this->os->statusMessage ( "xMySQL", "xUpdate", "Field count does not match value count. Executeion aborted.", 2 ) : 0;
			return false;
		}
		
		$q = "UPDATE $table SET ";
		for ( $i=0; $i<count ( $fields ); $i++ )
		{
			$q .= $fields[$i] . "=";
			( $values[$i] != "now()" && $values[$i] != "NULL" ) ? $q .= "'" . $values[$i] . "'" : $q .= $values[$i];
			( $i < ( count ( $fields ) - 1 ) ) ? $q .= ", " : 0;
		}
		( $where ) ? $q .= " WHERE $where" : 0;
		
		if ( $this->xConnect () )
		{
			if ( @mysql_query ( $q, $this->conn_id ) )
			{
				$x = @mysql_affected_rows ( $this->conn_id );
				( $this->os ) ? $this->os->statusMessage ( "xMySQL", "xUpdate", "Executed. $x record(s) updated.", 1 ) : 0;
				$this->xClose ();
				return $x;
			}
			else
			{
				( $this->os ) ? $this->os->statusMessage ( "xMySQL", "xUpdate", "Failed executing query '$q'. MySQL said: " . mysql_error () . ".", 2, mysql_errno () ) : 0;
				return false;
			}
		}
		else
		{
			( $this->os ) ? $this->os->statusMessage ( "xMySQL", "xUpdate", "Failed connecting to MySQL host.", 2 ) : 0;
			return false;
		}
	} // xUpdate ------------------------------------------------------------- end -
}
?>
Return current item: xMySQL