PHP ActiveRecord

tablepre = TABLE_PREFIX;
        $this->class = get_class($this);
        $this->table = $this->tablepre . strtolower($this->class);
        $this->data = array();
        $this->connect();
    }

    private function connect() {
        if(!self::$link) {
            self::$link = mysql_connect(DBHOST, DBUSER, DBPASS);
            mysql_select_db(DBNAME);
        }
        return self::$link;
    }

    public function __set($name, $value) {
        $this->data[$name] = $value;
    }

    private function implodefields($cond) {
        $fields = array();
        foreach($cond as $key => $value) {
            $value = mysql_real_escape_string($value);
            $fields[] = "`$key`='$value'";
        }
        return implode(', ', $fields);
    }

    public function add() {
        $fields = $this->implodefields($this->data);
        $sql = "INSERT INTO `{$this->table}` SET $fields";
        $this->query($sql);
    }

    public function findById($id) {
        $sql = "SELECT * FROM `{$this->table}` WHERE `{$this->primaryKey}`='$id' LIMIT 1";
        $data = $this->getOne($sql);
        return $this->makeObjFromArray($data);
    }

    private function makeObjFromArray($data) {
        $obj = new $this->class;
        foreach($data as $key => $value) {
            $obj->$key = $value;
        }
        return $obj;
    }

    private function query($sql) {
        echo $sql . "\n";
        return mysql_query($sql, self::$link);
    }

    private function getOne($sql) {
        $data = $this->query($sql);
        if($data) {
            $item = mysql_fetch_assoc($data);
            return $item;
        }
        return false;
    }
}

class User extends ActiveRecord {
    var $primaryKey = 'id';
}

$user = new User();
$user->name = 'Woody';
$user->email = 'xxx@hotmail.com';
$user->add();

$user = $user->findById(1);
print_r($user);

原文地址:  http://www.phpig.net/showthread.php?tid=310

73 thoughts on “PHP ActiveRecord

  1. Pingback: Leg Workouts For women

  2. Pingback: Jack3d

  3. Pingback: Linkaufbau

  4. Pingback: Lisbon hotels

  5. Pingback: make money with iphone apps

  6. Pingback: lunettes

  7. Pingback: ray-ban

  8. Pingback: divorce law in pennsylvania

  9. Pingback: hydroponics stores in california

  10. Pingback: carrara marble tiles sydney

  11. Pingback: Jimmy Choo Solbriller

  12. Pingback: Kangaroo Island Holiday Homes

  13. Pingback: http://www.banner4.com

  14. Pingback: http://www.24hbailbonds.com/CA/whittier.htm

  15. Pingback: divorce attorneys in pittsburgh

  16. Pingback: gafas carrera jocker

  17. Pingback: 21st century books

  18. Pingback: tin bullion

  19. Pingback: Shane Hackett Looking Glass Funds

  20. Pingback: free web hosting

  21. Pingback: dresses

  22. Pingback: sexe adult

  23. Pingback: adult social network

发表评论