Location: PHPKode > projects > WCL - Web Control Library for PHP > DataGrid/DataSource.php
<?php
/*
 * 	(C) Copyright by Christian Möller
 * 	All Rights reserved
 *
 * 	This file is part of the WCL (Web Control Library).
 *
 *  WCL 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 3 of the License, or
 *  (at your option) any later version.
 *
 *  Foobar 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 WCL.  If not, see <http://www.gnu.org/licenses/>.
 */


class DataSource {
	
	var $columns = array(),
		$rows	= array(),
		$name;
	
	function DataSource($name) {
		$this->name = $name;
	}
	
	function addColumn($name, $text) {
		$this->columns[$name] = $text;
	}
	
	function setColumns($columns) {
		$this->columns = $columns;
	}
	
	function addRow($row) {
		if (count($row) == count($this->columns))
			$this->rows[] = $row;
		else 
			die ("insufficent number of arguments supplied to datasource ".$this->name);
	}
	
	function clearRows() {
		$this->rows = array();
	}
	
	function clear() {
		$this->clearRows();
		$this->columns = array();
	}
	
	function fromPrefetch($prefetch) {
		$this->columns = array();
		$this->rows = array();
		
		$first_entry = true;
		foreach ($prefetch as $row) {
			$new_row = array();
			if ($first_entry) {
    			$first_entry = false;
    			foreach ($row as $key=>$value) {
    				$this->addColumn($key, $key);
    			}
    		}
			foreach ($row as $key=>$value) {
				$new_row[] = $value;
			}
			$this->addRow($new_row);
		}
	}
	
	function fromSQLTable($handle, $table, $items = false, $filter = false) {
		
		$this->columns = array();
		$this->rows = array();
		
		foreach ($items as $item=>$item_Text) {
			$this->addColumn($item, $item_Text);
		}
		
		$query = "SELECT * FROM ".$table;
		if ($filter) 
			$query .= " WHERE ".$filter;

		$res = mysql_query($query, $handle) or die("Error: The MySQL handle you specified is not valid.");
		
		$first_entry = true;
		
		while ($row = mysql_fetch_assoc($res)) {
    		$new_row = array();
    		
    		if (!$items && $first_entry) {
    			$first_entry = false;
    			foreach ($row as $key=>$value) {
    				$this->addColumn($key, $key);
    			}
    		}
    		
    		if ($items) {
    			foreach ($items as $item=>$item_text) {
    				$new_row[] = $row[$item];
    			}
    		} else 
    		{
    			$new_row = $row;
    		}
    		$this->addRow($new_row);
		}
	}
}

?>
Return current item: WCL - Web Control Library for PHP