<?php

/*
The DB Table represented by the model:

FavCereals ( ID is primary key, and thus unique )

ID | Name  | Cereal
----------------------------
1  | Jim   | Fruit Loops
2  | Gui   | Kix
3  | Bob   | Fruit Loops

*/

class FavCereals extends Model
{
  
//properties representing the table columns
  
var $ID 0;
  var 
$Name '';
  var 
$Cereal '';
  
//to hold the result set generated by the query
  
var $resultSet null;
  
//constructor
  
function FavCereals()
  {
    
parent::Model();
  }
  
//property setter methods
  
function setID($ID)
  {
    
$this->ID $ID;
  }

  function 
setName($Name)
  {
    
$this->Name $Name;
  }

  function 
setCereal($Cereal)
  {
    
$this->Cereal $Cereal;
  }
  
//the select that generates the SQL and executes the query
  
function select()
  {
    
$whereClauseSet false;
    
$query "SELECT ID,Name,Cereal FROM FavCereals";
    if(
$this->ID 0)
    {
      
$whereClause $whereClauseSet 'AND' 'WHERE';
      
$query .= sprintf(" %s ID = %s",$whereClause,$this->ID);
      
$whereClauseSet true;
    }
    if(!empty(
$this->Name))
    {
      
$whereClause $whereClauseSet 'AND' 'WHERE';
      
$query .= sprintf(" %s Name = '%s'",$whereClause,$this->Name);
      
$whereClauseSet true;
    }
    if(!empty(
$this->Cereal))
    {
      
$whereClause $whereClauseSet 'AND' 'WHERE';
      
$query .= sprintf(" %s Cereal = '%s'",$whereClause,$this->Cereal);
      
$whereClauseSet true;
    }
    
$this->resultSet $this->db->query($query);
    
$this->next();
  }
  
//the infamous 'next' which helps iterate the results and sets the appropriate propeties
  
function next()
  {
    
$returnVal false;
    if(!
is_null($this->resultSet))
    {
      while(
$row $this->resultSet->result())
      {
        
$this->ID $row->ID;
        
$this->Name $row->Name;
        
$this->Cereal $row->Cereal;
        
$returnVal true;
        break;
      }
    }
    return 
$returnVal;
  }
}


//Getting all records:
$ALLFavCereals = new FavCereals();
$ALLFavCereals->select();
//$ALLFavCereals ->ID, ->Name, and ->Cereal now contain the data from the first row
if($ALLFavCereals->next()){ /* $ALLFavCereals ->ID, ->Name, and ->Cereal now contain the data from the SECOND row */ }


//Getting a single record by user ID
$SingleFavCereal = new FavCereals();
$SingleFavCereal->setID(1);
$SingleFavCereal->select();
//$SingleFavCereal ->ID, ->Name, and ->Cereal now contain the data from the first and only row--the one with ID of 1
if($SingleFavCereal->next()){ /* next() will return false so $SingleFavCereal ->ID, ->Name, and ->Cereal nstill contains the data from the first and only row--the one with ID of 1 */ }

//etc etc etc
?>