Location: PHPKode > scripts > phpDbObject > phpdbobject/dbobject.class.php
<?php
/**
 * holds base class for all objects in DB
 *
 * @package DbObject
 * @author Sebastian Mendel <info at sebastianmendel dot de>
 * @copyright &copy; 2005 Sebastian Mendel <info at sebastianmendel dot de>
 */

require_once 'DateTime.class.php';

/**
 * base class for all objects in DB
 *
 * @package DbObject
 * @author Sebastian Mendel <info at sebastianmendel dot de>
 * @copyright &copy; 2005 Sebastian Mendel <info at sebastianmendel dot de>
 * @since 2004-08-12
 */
class DBObject
{
    /**
     * @var integer $id unique customer id
     */
    var $id = 0;
    
    /**
     * @var string name
     */
    var $name = '';
    
    /**
     * @var array $errors aray of errors
     */
    var $errors = array();
    
    /**
     * @var result mysql_result
     */
    var $result = NULL;
    
    /**
     * @var string sql sql-statement
     */
    var $sql = '';
    
    /**
     * @var string timestamp last change (yyyy-mm-dd hh:mm:ss)
     */
    var $date_last_change = '0000-00-00 00:00:00';
    
    /**
     * @var string timestamp last change (yyyy-mm-dd hh:mm:ss)
     */
    var $date_created = '0000-00-00 00:00:00';
    
    /**
     * constructor
     *
     * @param integer|array $param unique objectid or aray of object-properties
     */
    function __construct( $param = NULL )
    {
        if ( is_numeric( $param ) )
        {
            $this->setId( $param );
        }
        elseif ( is_array( $param ) )
        {
            $this->set( $param );
        }
        
        if ( $this->getId() > 0 )
        {
            $this->loadById();
        }
        
        if ( is_array( $param ) )
        {
            $this->set( $param );
        }
    }
    
    /**
     * @return string
     */
    function __toString()
    {
        return $this->getName();
    }
    
    /**
     * sets member-properties
     *
     * @param array $properties
     * @param string $context
     * @return integer number of properties set
     */
    function set( $properties, $context = '' )
    {
        if ( ! is_array($properties) || count($properties) < 1 )
        {
            return false;
        }
        
        // we dont care case-sensitivity and '_', ' ' and '.'
        // '_Telefon Gesch.' == 'telefongesch'
        // in given fields ...
        $removes = array( '_', ' ', '.' );
        
        // PHP5
        //$unsaves = array( 'ß',  'ä',  'ö',  'ü' );
        //$saves   = array( 'ss', 'ae', 'oe', 'ue' );
        
        // PHP4
        $unsaves = array( 'ß',  'ä',  'ö',  'ü',  'Ä',  'Ö',  'Ü' );
        $saves   = array( 'ss', 'ae', 'oe', 'ue', 'Ae', 'Oe', 'Ue' );
        
        $set = 0;
        foreach ( $properties as $property => $value )
        {
            $property = str_replace( $removes, '', $property );
            
            // PHP5
            //$property = str_ireplace( $unsaves, $saves, $property );
            
            // PHP4
            $property = str_replace( $unsaves, $saves, $property );

            if ( method_exists( $this, 'set' . $context . $property) )
            {
                $property = 'set' . $context . $property;
                $this->$property( $value );
                $set++;
            }
        }
        return $set;
    }
    
    /**
     * sets objekt properties from first row in result
     * and frees the result
     *
     * @param mysql_result $result
     * @return boolean true or false
     */
    function setFromResult( $result = NULL )
    {
        if ( false === $this->set( $this->fetchRow( $result ) ) )
        {
            return false;
        }
        
        $this->freeResult();
        
        return true;
    }
    
    /**
     * loads object by id
     * 
     * @uses $this->getTableName()
     * @uses $this->getId()
     * @uses $this->setError()
     * @uses $this->load()
     * 
     * @return boolean true|false
     */
    function loadById()
    {
        $this->where = array();
        $this->where[] = '`' . $this->getTableName() . '`.`id` = ' . (int) $this->getId();
        
        return $this->load();
    }
    
    /**
     * loads data from DB by given options
     * 
     * @uses $this->getTableName()
     * @uses $this->sql
     * @uses $this->query()
     * @uses $this->numRows()
     * @uses $this->setFromResult()
     * @uses implode()
     * 
     * @param array where-conditions
     * 
     * @return boolean true|false
     */
    function load()
    {
        $this->sql = '
             SELECT *
               FROM `' . $this->getTableName() . '`
              WHERE ' . implode( ' AND ', $this->where ) . '
              LIMIT 1';

        $this->query();

        if ( $this->numRows( 0 ) )
        {
            return false;
        }

        return $this->setFromResult();
    }

    /**
     * return last error message
     * 
     * @uses $this->$errors to return and remove the first value
     * @return string error-message
     */
    function getError()
    {
        return array_shift( $this->errors );
    }
    
    /**
     * adds error to the error-stack
     * 
     * @uses $this->$errors to add one value at the end
     * @param string $error
     */
    function setError( $error )
    {
        array_push($this->errors, $error);
    }
    
    /**
     * returns true if error-stack is not empty
     * 
     * @uses $this->$errors to check if empty
     * @param string $error
     * @return boolean true|false
     */
    function error( $error = null )
    {
        if ( null === $error )
        {
            return (bool) count($this->errors);
        }
        
        $this->setError( $error );
    }
    
    /**
     * deletes object from DB
     * 
     * @uses $this->getTableName()
     * 
     * @static
     * @param integer $id unique object ID
     * @param string $table name of table
     */
    function _delete( $id, $table )
    {
        DBOBject::query( 'DELETE FROM `' . $table . '` WHERE `id` = ' . (int) $id );
    }

    /**
     * überprüft ob alle Felder von $required_fields in $given_fields
     * vorhanden sind und gibt die Fehlenden Felder zurück
     *
     * @static
     * @param array|string $required_fields benötigte Felder
     * @param array $given_fields vorhanden Felder
     *
     * @return array|string $missing_fields fehlende Felder
     */
    function checkForRequiredFieldsInArray( $required_fields, $given_fields )
    {
        $missing_fields = array();
        $return_as_string = false;
        
        if ( is_string( $required_fields ) )
        {
            $required_fields = explode( ',', $required_fields );
            $return_as_string = true;
        }
        
        // we dont care case-sensitivity and '_', ' ' and '.'
        // '_Telefon Gesch.' == 'telefongesch'
        // in fieldnames ...
        $removes = array( '_', ' ', '.' );
        
        // PHP5
        //$unsaves = array( 'ß', 'ä', 'ö', 'ü' );
        //$saves   = array( 'ss', 'ae', 'oe', 'ue' );
        
        // PHP4
        $unsaves = array( 'ß', 'ä', 'ö', 'ü', 'Ä', 'Ö', 'Ü' );
        $saves   = array( 'ss', 'ae', 'oe', 'ue', 'Ae', 'Oe', 'Ue' );
        
        
        foreach ( $given_fields as $key => $val )
        {
            $key = str_replace( $removes, '', $key );

            // PHP5
            //$key = str_ireplace( $unsaves, $saves, $key );
            
            // PHP4
            $key = str_replace( $unsaves, $saves, $key );
            $key = strtolower( $key );
            
            // we also remove spaces from beginning and the end
            // in the values
            $given_fields[$key] = trim( $val );
        }
        
        // ... and in required fields
        foreach ( $required_fields as $field )
        {
            $_field = str_replace( $removes, '', $field );

            // PHP5
            //$_field = str_ireplace( $unsaves, $saves, $_field );
            
            // PHP4
            $_field = str_replace( $unsaves, $saves, $_field );
            $_field = strtolower( $_field );
            
            if ( empty( $given_fields[$_field] ) )
            {
                $missing_fields[] = $field;
            }
        }
        
        if ( $this && count( $missing_fields ) > 0 )
        {
            $this->error( 'Bitte alle benötigten (*) Felder ausfüllen (' . implode( ', ', $missing_fields ) . ')' );
        }
        
        if ( $return_as_string )
        {
            return implode( ', ', $missing_fields );
        }
        
        return $missing_fields;
    }
    
    /**
     * @param array|string $required_fields
     * @param array $given_fields
     * @return array|string
     */
    function checkForm( $required_fields, $given_fields )
    {
        return $this->checkForRequiredFieldsInArray( $required_fields, $given_fields );
    }
    
    /**
     * updates or insert data in db
     * 
     * @uses $this::insert() if $this::getId() is 0
     * @uses $this::update() if $this::getId() is not 0
     * @uses $this::getId() to determine if update or insert is required
     * 
     * @return boolean true|false
     */
    function save()
    {
        if ( $this->getId() === 0 )
        {
            $return = $this->insert();
            $this->setId( $this->lastInsertId() );
            return $return;
        }
        else
        {
            return $this->update();
        }
    }
    
    /**
     * sets the unique id for this object
     *
     * @author Sebastian Mendel <info at sebastianmendel dot de> 
     * @since 2004-08-12
     *
     * @param integer $id unique object-id
     */
    function setId( $id )
    {
        $this->id = (int) $id;
    }
    
    /**
     * returns the unique ID for this object
     *
     * @author Sebastian Mendel <info at sebastianmendel dot de> 
     * @since 2004-08-12
     *
     * @uses $this->id as return value
     * @return integer id
     */
    function getId()
    {
        return $this->id;
    }
    
    /**
     * sets the name for this object
     *
     * @author Sebastian Mendel <info at sebastianmendel dot de> 
     * @since 2005-02-14
     *
     * @param string $name
     */
    function setName( $name )
    {
        $this->name = trim( $name );
    }
    
    /**
     * returns the name for this object
     *
     * @author Sebastian Mendel <info at sebastianmendel dot de> 
     * @since 2005-02-14
     *
     * @uses $this->name as return value
     * @return string name
     */
    function getName()
    {
        return $this->name;
    }
    
    /**
     * @param string $date_last_change (yyyy-mm-dd hh:mm:ss)
     */
    function setDateLastChange( $date_last_change )
    {
        $this->date_last_change = DateTime::get( $date_last_change );
    }
    
    /**
     * @return string $this->date_last_change
     */
    function getDateLastChange()
    {
        return $this->date_last_change;
    }
    
    /**
     * @param string $date_created (yyyy-mm-dd hh:mm:ss)
     */
    function setDateCreated( $date_created )
    {
        $this->date_created = DateTime::get( $date_created );
    }
    
    /**
     * @return string $this->date_created
     */
    function getDateCreated()
    {
        return $this->date_created;
    }
    
    /**
     * runs a given sql-query and returns result
     *
     * @author Sebastian Mendel <info at sebastianmendel dot de> 
     * @since 2004-08-12
     *
     * @uses dbaction() to perform sql-query
     *
     * @static
     * @param string $sql sql-statement
     * @return mixed result
     * @uses dbaction()
     * @uses $this->result
     * @uses $this->sql
     */
    function query( $sql = NULL )
    {
        if ( NULL === $sql )
        {
            if ( ! isset( $this ) )
            {
                trigger_error( 'called staticaly without parameter', E_USER_ERROR );
                return false;
            }
            
            if ( empty( $this->sql ) )
            {
                trigger_error( 'query is empty or not set', E_USER_ERROR );
                return false;
            }
            
            $this->result = dbaction( $this->sql );
            return $this->result;
        }
        
        $sql = trim( $sql );
        
        if ( empty( $sql ) )
        {
            trigger_error( 'parameter is empty', E_USER_ERROR );
            return false;
        }
        
        if ( isset( $this ) )
        {
            $this->sql = $sql;
            $this->result = dbaction( $this->sql );
            return $this->result;
        }
        
        // called static
        return dbaction( $sql );
    }
    
    /**
     * returns number of rows in resultset
     * if first paramter $rownumber is given it returns true if numbers
     * of rows in result is equal to $rownumber otherwise false
     *
     * @static 
     * @uses mysql_num_rows()
     * @param integer $rownumber
     * @return mixed true|false|rownumber
     */
    function numRows( $rownumber = NULL )
    {
        if ( false === $this->evaluateResult() )
        {
            trigger_error( 'no result found', E_USER_WARNING );
            return false;
        }
        
        if ( NULL === $rownumber )
        {
            return mysql_num_rows( $this->result );
        }
        
        if ( mysql_num_rows( $this->result ) == (int) $rownumber )
        {
            return true;
        }
        
        return false;
    }
    
    /**
     * returns first single value of given resultset or sql-query
     *
     * @param string|mysql_result $result
     * @return string|float|integer|NULL|boolean value
     */
    function fetchValue( $result = NULL )
    {
        if ( ! isset( $this ) || ! is_a( $this, 'DBObject' ) )
        {
            $dbobject =& new DBObject();
            return $dbobject->fetchValue( $result );
        }
        
        if ( false === $this->evaluateResult( $result ) )
        {
            return false;
        }
        
        if ( $this->numRows( 0 ) )
        {
            return false;
        }
        
        return mysql_result( $this->result, 0 );
    }
    
    /**
     * returns one row from result
     *
     * @static 
     * @uses $this->result to get row
     * @uses mysql_fetch_assoc()
     * @param string|mysql_result $result
     * @return array row
     */
    function fetchRow( $result = NULL )
    {
        if ( ! isset( $this ) || ! is_a( $this, 'DBObject' ) )
        {
            $dbobject =& new DBObject();
            return $dbobject->fetchRow( $result );
        }
        
        if ( false === $this->evaluateResult( $result ) )
        {
            return false;
        }
        
        return mysql_fetch_assoc( $this->result );
    }
    
    /**
     * returns all rows in the resultset in one array
     *
     * @static 
     * @param string|mysql_result $result
     * @param string $key field-name used as $key for array
     * @param string $value value-name used as value for array
     * @return array resultrows
     */
    function fetchResult( $result = NULL, $key = NULL, $value = NULL )
    {
        if ( ! isset( $this ) || ! is_a( $this, 'DBObject' ) )
        {
            $dbobject =& new DBObject();
            return $dbobject->fetchResult( $result, $key, $value );
        }
        
        if ( false === $this->evaluateResult( $result ) )
        {
            return false;
        }
        
        $resultrows = array();
        
        if ( NULL === $key && NULL === $value )
        {
            while ( $row = $this->fetchRow() )
            {
                $resultrows[] = $row;
            }
        }
        elseif ( NULL === $key )
        {
            while ( $row = $this->fetchRow() )
            {
                $resultrows[] = $row[$value];
            }
        }
        elseif ( NULL === $value )
        {
            while ( $row = $this->fetchRow() )
            {
                $resultrows[$row[$key]] = $row;
            }
        }
        else
        {
            while ( $row = $this->fetchRow() )
            {
                $resultrows[$row[$key]] = $row[$value];
            }
        }
        
        return $resultrows;
    }
    
    /**
     * checks given result and set it or execute it
     * if not given, it checks $this->result
     *
     * @param string|mysql_result $result
     * @return boolean success
     */
    function evaluateResult( $result = NULL )
    {
        if ( is_string( $result ) )
        {
            // its a string, so it must be a query, execute it ...
            if ( false === $this->query( $result ) )
            {
                return false;
            }
        }
        elseif ( is_resource( $result )
                && get_resource_type( $result ) === 'mysql result' )
        {
            $this->result = $result;
        }
        elseif ( ! is_resource( $this->result )
                || ! get_resource_type( $this->result ) === 'mysql result' )
        {
            if ( false === $this->query() )
            {
                return false;
            }
        }
        
        return true;
    }
    
    /**
     * frees the result
     *
     * @static 
     * @param mysql_result $result
     * @uses $this->result to free it
     * @uses mysql_free_result()
     */
    function freeResult( $result = NULL )
    {
        if ( NULL === $result )
        {
            mysql_free_result( $this->result );
        }
        else
        {
            mysql_free_result( $result );
        }
    }
    
    /**
     * escpaes String for use in sql-query
     *
     * @static 
     * @param string $string
     * @return string escaped string
     * @uses mysql_real_escape_string()
     */
    function escapeString( $string )
    {
        return mysql_real_escape_string( $string );
    }
    
    /**
     * returns ID for last inserted Datarow
     *
     * @static 
     * @return integer id
     * @uses mysql_insert_id()
     */
    function lastInsertId()
    {
        return mysql_insert_id();
    }
}
?>
Return current item: phpDbObject