patternphpMinor
PHP OOP - Does this database reading class make sense?
Viewed 0 times
thisreadingphpmakedatabasesensedoesclassoop
Problem
After a whole night of work I finally have my first useful class - for reading database.
It works like a charm, but if you got a moment, please take a glance and give me feedback. Harsh criticism welcome.
Please note that security is not addressed yet, as well as usual SQL clauses, but I'd like to know am I on the right way to writing better software.
Here it is:
}
Have I wrote an actual class that makes sense, or just a glorified function?
Thanks.
It works like a charm, but if you got a moment, please take a glance and give me feedback. Harsh criticism welcome.
Please note that security is not addressed yet, as well as usual SQL clauses, but I'd like to know am I on the right way to writing better software.
Here it is:
class DatabaseRead {
protected $dbh; // Database handle connection
public $columns = array(); // Columns to be read
public $table; // Table to be read from
public $resultSet = array(); // Returned results
public function __construct( $dbh, $columns, $table ) {
$this->dbh = $dbh;
$this->columns = $columns;
$this->column = '';
$this->table = $table;
$this->resultSet = array();
$read_database = $this->dbh->query('SELECT ' . implode(',' , $this->columns) . ' FROM ' . $this->table);
while ($row = $read_database->fetch()) {
foreach($this->columns as $this->column) {
$this->resultSet[$this->column] = $row[$this->column];
}
}
return $this->resultSet;
}}
Have I wrote an actual class that makes sense, or just a glorified function?
Thanks.
Solution
Why don't you split the "constructor" part and the "get the values" part?
Code :
Usage :
Code :
class Database {
protected $dbh; // Database handle connection
public function __construct( $dbh) {
$this->dbh = $dbh;
}
public function getResults($columns,$table)
{
$resultSet = array();
$read_database = $this->dbh->query('SELECT ' . implode(',' , $columns) . ' FROM ' . $table);
while ($row = $read_database->fetch()) {
foreach($columns as $column) {
$resultSet[$column] = $row[$column];
}
}
return $resultSet;
}
}Usage :
$db = new Database($dbh);
$db->getResults($columns, $table);Code Snippets
class Database {
protected $dbh; // Database handle connection
public function __construct( $dbh) {
$this->dbh = $dbh;
}
public function getResults($columns,$table)
{
$resultSet = array();
$read_database = $this->dbh->query('SELECT ' . implode(',' , $columns) . ' FROM ' . $table);
while ($row = $read_database->fetch()) {
foreach($columns as $column) {
$resultSet[$column] = $row[$column];
}
}
return $resultSet;
}
}$db = new Database($dbh);
$db->getResults($columns, $table);Context
StackExchange Code Review Q#10738, answer score: 4
Revisions (0)
No revisions yet.