Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- DATABASE-OBJECTS.PHP
- <?php
- require_once('initialize.php');
- class DatabaseObjects{
- private $dbh;
- static $table_name;
- static $db_fields;
- public function __construct(){
- global $MySQLDatabase;
- global $news;
- $this->dbh = $MySQLDatabase->open_connection();
- // Convert Table Fields in to Attributes
- static::$db_fields = $this->get_dbFields(static::$table_name);
- foreach(static::$db_fields as $field){
- $this->$field = "";
- }
- }
- // Get Table Fields from the Database
- public function get_dbFields($table_name){
- $sql = 'DESCRIBE ' . $table_name ;
- $query = $this->dbh->prepare($sql);
- $query->execute();
- $result = $query->fetchAll(PDO::FETCH_OBJ);
- // Get the quantity of the Table Columns
- $count = count($result);
- $field = array();
- // Loop through each column to get the 'Field'
- // ($count - 1) -> $count is minus 1 because array count starts with zero
- // Example : Table Have 8 Columns
- // $count will read it as 1 - 8 while array ($result[i]) reads it as 0 - 7
- for($i = 0; $i <= ($count - 1); $i++){
- $field[] = $result[$i]->Field;
- }
- return $field;
- }
- public function find_all(){
- $sql = 'SELECT * FROM ' . static::$table_name;
- return $this->find_by_sql($sql);
- }
- private function find_by_sql($sql){
- $query = $this->dbh->prepare($sql);
- $query->execute();
- $array_object = array();
- while($rows = $query->fetch(PDO::FETCH_ASSOC)){
- $array_object[] = $this->instantiate($rows);
- }
- return $array_object;
- }
- private function instantiate($record){
- $object = new self;
- foreach($record as $attribute => $value){
- if($this->has_attribute($attribute)){
- $object->$attribute = $value;
- }
- }
- return $object;
- }
- private function has_attribute($attribute){
- return array_key_exists($attribute, $this->attributes());
- }
- private function attributes(){
- $attributes = array();
- foreach(static::$db_fields as $field){
- $attributes[$field] = $field;
- }
- return $attributes;
- }
- }
- ?>
- -----------------------------------------------
- NEWS-CLASS.PHP
- <?php
- require_once('initialize.php');
- class News extends DatabaseObjects{
- static $table_name = 'news';
- static $db_fields;
- }
- $news = new News();
- ?>
- ----------------------------------------------
- NEWS.PHP
- <?php include('../includes/initialize.php');
- $r = $news->find_all();
- foreach($r as $a){
- echo '<h1>'.$a->title.'</h1>';
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment