<?php
define('DBHOST', 'localhost');
define('DBUSER', 'root');
define('DBPASS', '');
define('DBNAME', 'test');
define('TABLE_PREFIX', 't_');
class ActiveRecord {
private $tablepre;
private $class;
private $table;
private static $link;
private $data;
public $primaryKey = 'id';
public function __construct() {
$this->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 = '热电影';
$user->email = 'www.redianying.com';
$user->add();
$user = $user->findById(1);
print_r($user);
共同学习,写下你的评论
评论加载中...
作者其他优质文章