<?php
/**
* db
*
* # Description #
* this simple db class makes your scripts able to access easily your MySQL database
*
* Features:
* 1. easy Methods like newEntry(), getEntry() and updateEntry() to manipulate database records
* 2. results are associative arrays and are simple to handle
* 3. method newQuery() allowes you do any personalized query to your database
* 4. secure errorhandling with switchable debug-mode and errorlog with two log-files
*
* @package simple database handling
* @author R.Zotin <rusty@zotin.com>
* @copyright Copyright (c) 2004
* @version 2.1 engl.
* @access public
*/
class db
{
#### START EDIT YOUR DATABASE-VARIABLES HERE ######################################
// CONFIGURATION-VARIABLE: contains DB-server name (host)
var $db_server = "localhost";
// CONFIGURATION-VARIABLE: contains DB-name
var $db_name = "test";
// CONFIGURATION-VARIABLE: contains DB-user name
var $db_usr = "root";
// CONFIGURATION-VARIABLE: contains DB-password
var $db_pwd = "";
// CONFIGURATION-VARIABLE: contains name of directory to logfiles ex.: "logs" (set htaccess-password to it!)
var $log_dir = "logs"; //
// CONFIGURATION-VARIABLE: contains the name of the logfile to catch all DB-Errors (usefull to DEBUG)
var $log_errors = "dbClass_errors.log"; //
// CONFIGURATION-VARIABLE: contains the name of the logfile to catch the last DB-Error (usefull to DEBUG)
var $log_lasterr= "dbClass_lasterror.log"; //
// CONFIGURATION-VARIABLE: contains URL to your homeindex for redirection if debug-mode ist set to FALSE
var $home_url = "http://localhost"; //
// CONFIGURATION-VARIABLE: to switch debug-mode (on|off) TRUE or FALSE
var $debug = TRUE; //
// CONFIGURATION-VARIABLE: (on|off) TRUE or FALSE, secure output of errors in case of FALSE
var $show_errors= TRUE;
#### STOP EDIT YOUR DATABASE-VARIABLES HERE! #####################################
####################################################################################
#### Do NOT EDIT anything after this line! #########################################
####################################################################################
var $table; // contains default database tablename
var $link; // contains link to database
var $num_rows; // contains number of affected rows since last query
var $insert_id; // contains an index (auto_increment) since last new entry
var $ERR_PREFIX = "dbClass.inc.php tried: db::"; // contains prefix for the error messages
/**
* db::db()
* # Description: #
* This is the constructor of the db class. You should set the default tablename here for the first access.
* @param string $table_str
* @access public
* @return
**/
function db($table_str = "") // Kommentar
{
$this->table = $table_str;
$this->link = mysql_pconnect($this->db_server, $this->db_usr, $this->db_pwd) or
die("<html><body>Sorry, our database seemes to be busy.\n
Please, try to acces our site later (or just wait about 10 seconds for javascript-autorefresh).\n<script language=\"JavaScript\">window.setTimeout(\"window.location.reload()\", 10000);</script></body></html>");
mysql_select_db($this->db_name, $this->link) or
die($this->errorlog("Database ".$this->db_name." could not be found"));
}
/**
* db::errorlog()
* # Description: #
* Intern private class method to store all SQL-Errors with timestamp and scriptname in a logfile.
* @param string $error_string
* @access protected
* @return string
**/
function errorlog($error_string)
{
if (!is_dir($this->log_dir)) mkdir ($this->log_dir, 0774);
$stamp="File: ".$_SERVER['PHP_SELF']." Time: ".date("Y-m-d H:i:s")." ERROR: ";
$fp = @fopen($this->log_dir.'/'.$this->log_errors,"a");
fputs($fp, $stamp.$error_string);
fclose($fp);
$fp = @fopen($this->log_dir.'/'.$this->log_lasterr,"w");
fputs($fp, $stamp.$error_string);
fclose($fp);
if ($this->debug){
if ($this->show_errors) {
$returnstring='<font color="red">'.$error_string.'</font>';
} else {
$returnstring="Database <a href=\"{$this->log_dir}/{$this->log_lasterr}\">error</a> appeared. Apologies. Webmasters should take a look in their <a href=\"{$this->log_dir}/{$this->log_errors}\">logs</a>! [secure database handling by <a href=\"http://www.zotin.com/resources\" target=\"_blank\">www.zotin.com/resources</a> ©2004]";
}
} else {
$returnstring='<meta http-equiv="refresh" content="2; URL='.$this->home_url.'">';
}
return $returnstring;
}
/**
* db::newQuery()
* # Description: #
* Execute any MySQL query with this method. It will simply return the result provided your query was successful.
* @param string $query
* @param string $err_prefix
* @access public
* @result returns result provided your query was successful
**/
function newQuery($query,$err_prefix)
{
$result = mysql_query($query, $this->link) or
die( $this->errorlog($err_prefix."\n - MySQL-Query failed: ".$query."\n - ".mysql_error()."\n"));
$this->num_rows = @mysql_num_rows($result);
$this->insert_id = @mysql_insert_id();
return $result;
}
/**
* db::getEntry()
* # Description: #
* This method returns an multidimensional array with records wich fit to your WHERE clause.
* @param array $select_array
* @param string $where_str
* @param string $order_str
* @access public
* @return array multidimensional associative array
**/
function getEntry( $select_array, $where_str, $order_str)
{
$err_prefix = $this->ERR_PREFIX."getEntry(".var_export($select_array,TRUE).",".$where_str." ".$order_str.")";
$query = "SELECT ".implode(",", $select_array).
" FROM ".$this->table.
" WHERE $where_str $order_str";
$result = $this->newQuery($query,$err_prefix);
$entry = array();
for ($i = 0; $i < $this->num_rows; $i++)
{
$entry[] = mysql_fetch_array($result);
}
return $entry;
}
/**
* db::newEntry()
* # Description: #
* Create new records by using this method. You will need an associativ array withsome default values.
* @param array $insert_assocArray
* @return integer returns the auto_increment index value of the new record, provides that it is set in the database table.
**/
function newEntry($insert_assocArray)
{
$err_prefix = $this->ERR_PREFIX."newEntry(".var_export($insert_assocArray,TRUE).")";
$insertKeys=array();
$insertValues=array();
while (list ($feld, $wert) = each ($insert_assocArray))
{
array_push($insertKeys,$feld);
array_push($insertValues,$wert);
}
$query = "INSERT INTO ".$this->table." (".implode(",", $insertKeys).")".
" VALUES ('".implode("','", $insertValues)."')";
$result = $this->newQuery($query,$err_prefix);
// RETURN INDEX of LAST INSERT
return $this->insert_id;
}
/**
* db::updateEntry()
* # Description: #
* Update any value you want in records wich fit to your WHERE clause.
* @param array $update_assocArray
* @param string $where_str
* @return integer returns count of updated recordlines
**/
function updateEntry($update_assocArray,$where_str)
{
$err_prefix = $this->ERR_PREFIX."updateEntry(".var_export($update_assocArray, TRUE).",".$where_str.")";
$query = "UPDATE ".$this->table." SET ";
foreach($update_assocArray as $key => $value)
{
$query.= $key."='".$value."'";
if (next($update_assocArray)) {
$query.=", ";
}
}
$query.= " WHERE $where_str";
$result = $this->newQuery($query,$err_prefix);
// OPTIONAL: count updated lines
$entries = $this->num_rows;
return $entries;
}
/**
* db::deleteEntry()
* # Description: #
* Easily delete records which fit to your searchcondition. Optional $where_str can contain the LIMIT condition.
* @param string $where_str
* @return integer returns count of deleted lines
**/
function deleteEntry($where_str)
{
$err_prefix = $this->ERR_PREFIX."deleteEntry(".$whereStr.")";
$query = "DELETE FROM ".$this->table.
" WHERE $where_str";
$result = $this->newQuery($query,$err_prefix);
// OPTIONAL: get number of deleted lines
$entries = $this->num_rows;
return $entries;
}
/**
* db::entryExists()
* # Description: #
* Here you can prove if the record with certain condition already exists.
* @param string $where_str
* @return boolean returns TRUE if queried entry already exist and FALSE it it's not.
**/
function entryExists($where_str)
{
$err_prefix = $this->ERR_PREFIX."entryExists(".$where_str.")";
$query = "SELECT *".
" FROM ".$this->table.
" WHERE $where_str LIMIT 1";
if ($result = $this->newQuery($query,$err_prefix))
{
$entry = mysql_fetch_array($result);
mysql_free_result($result);
if (empty($entry)) return false;
return true;
} else return false;
}
}
?>