It's better practice to keep access to variables through methods (functions) instead of direct access.
Maybe you could try something like....
PHP Code:
class Select{
protected $Table, $Columns = array(), $Clauses = array(), $Result = false, $LastQuery = '';
public function __Construct($Table, array $Columns = null, array $Clauses = null){
$this->setTable($Table);
$this->addClause('1 = 1');
if($Columns != null){
$this->addColumns($Columns);
}
if($Clause != null){
$this->setClause($Clause);
}
}
public function setTable($Table){
$this->Table = (string)$Table;
}
public function addClauses(array $Clause){
$this->Clauses = array_merge($this->Clause, $Clause);
}
public function addColumn($Clause){
$this->Clauses[] = (string)$Clause;
}
public function addColumns(array $Columns){
$this->Columns = array_merge($this->Columns, $Columns);
}
public function addColumn($Column){
$this->Columns[] = $Column;
}
public function getResult(){
return $this->Result;
}
public function getLastQuery(){
return $this->LastQuery;
}
public function fetchArray(){
if($this->Result !== false){
return MySQL_Fetch_Array($this->Result);
}else{
return false;
}
}
public function execute(){
$Query = SPrintF('SELECT %s FROM %s WHERE %s', count($Columns) > 1 ? implode(', ', $Columns) : '*', $this->Table, implode(' AND ', $this->Clauses));
$Result = MySQL_Query($Query);
return $this->getResult();
}
}
I've just written it out here so it's untested, but it's implementation would be:
PHP Code:
<?php
$Select = new Select('Food', array('Name'));
$Select->execute();
echo '<h3>All Food:</h3>';
echo '<ul>';
while($row = $Select->fetchArray()){
printf('<li>%s</li>', $row['Name']);
}
echo '</ul>';
$Select->AddClause("Type = 'Fruit'");
$Select->execute();
echo '<h3>Just Fruit:</h3>';
echo '<ul>';
while($row = $Select->fetchArray()){
printf('<li>%s</li>', $row['Name']);
}
echo '</ul>';
$Select->AddClause("Name LIKE 'a%'");
$Select->execute();
echo '<h3>Just Fruit Beginning with A:</h3>';
echo '<ul>';
while($row = $Select->fetchArray()){
printf('<li>%s</li>', $row['Name']);
}
echo '</ul>';
A query class doesn't have many uses, but if you were to use one and base it on MySQL (PDO would be a much better option) then the above should be a good example.
Bookmarks