Code: Select all
<?php
require_once("database.php");
class User{
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
public static function find_all(){
return self::find_by_sql("select * from users");
}
public static function find_by_id($id=0){
global $database;
$result_array = self::find_by_sql("select * from users where id = {$id} LIMIT 1");
return !empty($result_array) ? array_shift($result_array) : false;
}
public static function find_by_sql($sql=""){
global $database;
$result_set = $database->query($sql);
$object_array = array();
while ($row = $database->fetch_array($result_set)){
$object_array[] = self::instantiate($row);
}
[color=#BF0000] return $object_array[];[/color]
}
private static function instantiate($record){
// could check that $record exists and is an array
$object = new self;
//$object->id = $record['id'];
//$object->username = $record['username'];
//$object->password = $record['password'];
//$object->first_name = $record['first_name'];
//$object->last_name = $record['last_name'];
foreach($record as $attribute=>$value){
if($object->has_attribute($attribute)){
$object->attribute = $value;
}
}
return $object;
}
private function has_attribute($attribute){
//get_object_vars returns an assosiative array with all attributes
// (includes private ones!) as the keys and their current values as the value
$object_vars = get_object_vars($this);
// we don't care about the value, we just want to know if the key exists
// Will return true or false
return array_key_exists($attribute , $object_vars);
}
}
Code: Select all
<?php
require_once("../includes/config.php");
require_once("../includes/database.php");
require_once ("../includes/user.php");
echo "<hr />";
$user = User::find_by_id(1);
echo $user->first_name . "<br />";
$users = User::find_all();
foreach ($users as $user) {
echo "User : ". $user->username ."<br />";
}
?>