Location: PHPKode > scripts > tgcSqlBuilder > include/tgcSqlBuilder/Insert.php
<?php
/**
 * $Id: Insert.php,v 1.1.1.1 2004/02/14 01:43:22 luckec Exp $
 *
 * Subclass of tgcSqlBuilder that helps to create INSERT sql-statements.
 *
 * @package     tgcSqlBuilder
 * @author      Carsten Lucke <hide@address.com>
 * @copyright   Carsten Lucke <http://www.tool-garage.de>
 */
 
 
 
 /**
 * No insert values specified for a query
 *
 * @access      public
 */
define('SQLBUILDER_ERROR_NO_INSERT_VALUES', 201);



/**
 * Subclass of tgcSqlBuilder that helps to create INSERT sql-statements.
 *
 * @package     tgcSqlBuilder
 * @access      public
 * @version     1.0.0
 * @author      Carsten Lucke <hide@address.com>
 */
class tgcSqlBuilder_Insert extends tgcSqlBuilder 
{
    
   /**
    * Tablename on which a sql-statement concerns.
    *
    * It's a numeric array, that contains the tablenames, that shall be used in an sql-statement.
    *
    * @access       private
    * @var          array           tablename
    */
    var $_tables;
    
   /**
    * Insert data.
    *
    * Array structure:
    * <pre>
    * array (
    *           $col1Name   =>  $col1Value,
    *           $col2Name   =>  $col2Value,
    *           ...
    *       )
    * </pre>
    *
    * @access       private
    * @var          array           insert data
    */
    var $_insert = array();
    
   /**
    * Raw Insert data.
    *
    * Array structure:
    * <pre>
    * array (
    *           statement1,
    *           statement2,
    *           ...
    *       )
    * </pre>
    *
    * @access       private
    * @var          array           insert data
    */
    var $_rawInsert = array();
    
    
    
   /**
    * Constructor
    *
    * @access       public
    * @param        object          $dbc            PEAR::DB connection object
    */
    function tgcSqlBuilder_Insert(&$dbc)
    {
        parent::tgcSqlBuilder($dbc);
    }
    
   /**
    * Generate the sql-statement.
    *
    * This method generates a query based on the object-information and returns it as a string.
    *
    * <code>
    * $sql      =   new tgcSqlBuilder_Insert($dbc);
    * $query    =   $sql->generateQuery();
    * </code>
    *
    * @access       public
    * @return       mixed           sql-statement or PEAR_Error (possible error(s): SQLBUILDER_ERROR_NO_INSERT_VALUES)
    */
    function generateQuery()
    {
        // check if a table has been specified
        if (empty($this->_tables))
        {
            return PEAR::raiseError (
                                        'You have to specifiy a tablename first',
                                        SQLBUILDER_ERROR_NO_TABLE_FOUND
                                    );
        }
        
        $query               =      'INSERT INTO ' . $this->_tables;
        
        $insertInformation   =      $this->_generateInsertInformation($this->_insert, $this->_rawInsert);
        if ($insertInformation != '') {
            $query          .=      ' ' . $insertInformation;
            $this->reset();
            
            return           $query;
        }
        
        return PEAR::raiseError (
                                        'No insert values found.',
                                        SQLBUILDER_ERROR_NO_INSERT_VALUES,
                                        null,
                                        null,
                                        'To generate a valid query you have to specify at least one insert value'
                                    );
    }
    
   /**
    * Generates the INSERT information.
    *
    * @access       private
    * @param        array       $insert         INSERT information
    * @param        array       $rawInsert      raw INSERT information
    * @return       string      statement for the query on success, else empty string
    */
    function _generateInsertInformation($insert, $rawInsert)
    {
        $information        =       '';
        
        if (count($insert) || count($rawInsert)) {
            $colNames       =       array_keys($insert);
            $values         =       array_map(array($this, 'escape'), array_values($insert));
            
            foreach ($rawInsert as $name => $value) {
                array_push($colNames, $name);
                array_push($values, $value);
            }
            
            $information    =       sprintf (" (%s) VALUES (%s)", implode(', ', $colNames), implode(', ', $values));
            $foundValues    =       true;
            return $information;
        }
        
        return '';
    }
    
   /**
    * Add the statements table.
    *
    * If you call this method twice, the tablename that was set in first call will be overwritten.
    *
    * <code>
    * $sql      =   new tgcSqlBuilder_Select($dbc);
    * $sql->addTable('users');
    * // now the generated sql-statement would look like: DELETE FROM users ...
    * </code>
    *
    * @access       public
    * @param        string          $tableName      tablename
    */
    function addTable($tableName)
    {
        $this->_tables      =   $tableName;
    }
    
   /**
    * Remove the tablename.
    *
    * @access       public
    */
    function removeTable()
    {
        $this->_tables      =   null;
    }
    
   /**
    * Add a value to insert.
    *
    * There are two ways of calling this method:
    *
    * <code>
    * // simple method-call
    * $sql      =       new tgcSqlBuilder_Insert($dbc);
    * $sql->addInsert('col_Username', 'superman');
    *
    * // complex method-call, you can add more than one insert with only one method-call
    * $insert   =       array   (
    *                               'col_Username'  =>  'superman',
    *                               'col_Email'     =>  'hide@address.com'
    *                           );
    * $sql->addInsert($insert);
    * </code>
    *
    * @access       public
    * @param        mixed           $colName        columnname or associative array containing pairs of $colName => $value
    * @param        mixed           $value          value to insert
    * @return       mixed           true on success, else PEAR_Error (possible error(s): SQLBUILDER_ERROR_INVALID_PARAM_COMBO)
    */
    function addInsert($colName, $value = null)
    {
        if (is_array($colName) && is_null($value)) {
            foreach ($colName as $key => $value) {
                $this->_insert[$key]    =   $value;
            }
            return true;
        }
        
        if (! is_null($colName) && ! is_null($value)) {
            $this->_insert[$colName]    =   $value;
            return true;
        }
        
        return PEAR::raiseError(    'Invalid parameter combination',
                                    SQLBUILDER_ERROR_INVALID_PARAM_COMBO,
                                    null,
                                    null,
                                    'You called this method with an invalid parameter combination.'
                                );
    }
    
   /**
    * Remove one or all insert columns.
    *
    * If you specify a columnname, then just this column's insert will be removed, else all inserts will be removed.
    *
    * @access       public
    * @param        string          $colName        columnname
    * @return       mixed           true on success, else PEAR_Error (possible error(s): SQLBUILDER_ERROR_COLUMN_DOES_NOT_EXIST)
    */
    function removeInsert($colName = null)
    {
        if(! is_null($colName)) {
            if (isset($this->_insert[$colName])) {
                unset($this->_insert[$colName]);
                return true;
            }
            
            return PEAR::raiseError (
                                        'Column doesn\'t exist',
                                        SQLBUILDER_ERROR_COLUMN_DOES_NOT_EXIST,
                                        null,
                                        null,
                                        'The column you tried to remove does not exist.'
                                    );
        }
        
        $this->_insert  =   array();
        return true;
    }
    
   /**
    * Add a raw INSERT statement
    *
    * There are two ways of calling this method:
    *
    * <code>
    * // simple method-call
    * $sql      =       new tgcSqlBuilder_Insert($dbc);
    * $sql->addInsert('creationTime', 'NOW()');
    *
    * // complex method-call, you can add more than one insert with only one method-call
    * $insert   =       array   (
    *                               'created'   =>  'NOW()',
    *                               'changed'   =>  'NOW()'
    *                           );
    * $sql->addInsert($insert);
    * </code>
    *
    * @access       public
    * @param        mixed           $colName        columnname or associative array containing pairs of $colName => $value
    * @param        mixed           $value          value to insert
    * @return       mixed           true on success, else PEAR_Error (possible error(s): SQLBUILDER_ERROR_INVALID_PARAM_COMBO)
    */
    function addRawInsert($colName, $value = null)
    {
        if (is_array($colName) && is_null($value)) {
            foreach ($colName as $key => $value) {
                $this->_rawInsert[$key]    =   $value;
            }
            return true;
        }
        
        if (! is_null($colName) && ! is_null($value)) {
            $this->_rawInsert[$colName]    =   $value;
            return true;
        }
        
        return PEAR::raiseError(    'Invalid parameter combination',
                                    SQLBUILDER_ERROR_INVALID_PARAM_COMBO,
                                    null,
                                    null,
                                    'You called this method with an invalid parameter combination.'
                                );
    }
    
   /**
    * Remove one or all insert columns.
    *
    * If you specify a columnname, then just this column's insert will be removed, else all inserts will be removed.
    *
    * @access       public
    * @param        string          $colName        columnname
    * @return       mixed           true on success, else PEAR_Error (possible error(s): SQLBUILDER_ERROR_COLUMN_DOES_NOT_EXIST)
    */
    function removeRawInsert($colName = null)
    {
        if(! is_null($colName)) {
            if (isset($this->_rawInsert[$colName])) {
                unset($this->_rawInsert[$colName]);
                return true;
            }
            
            return PEAR::raiseError (
                                        'Column doesn\'t exist',
                                        SQLBUILDER_ERROR_COLUMN_DOES_NOT_EXIST,
                                        null,
                                        null,
                                        'The column you tried to remove does not exist.'
                                    );
        }
        
        $this->_rawInsert  =   array();
        return true;
    }
    
   /**
    * Reset the object's whole information.
    *
    * @access       public
    */
    function reset()
    {
        $this->removeTable();
        $this->removeInsert();
        $this->removeRawInsert();
    }
    
}
?>
Return current item: tgcSqlBuilder