您可以以面向对象的方式访问 MySQL 表格。假设您有一个名为 Users 的表格,它包含以下字段:UserID、UserName、UserPassword、UserBirthday,您可以创建一个继承 DataObject 的 PHP 类并将其与该表格关联
<?php
class User extends DataObject {
protected static $_table = array('name' => 'Users', 'key' => 'UserID', 'auto' => 'UserID');
protected static $_propertyList = array('id' => 'UserID', 'name' => 'UserName', 'password' => 'UserPassword', 'birthday' => 'UserBirthday');
public static function GetAll() {
global $dbh;
$sql = 'SELECT * FROM Users';
$stmt = $dbh->query($sql);
$users = array();
while ($user = $stmt->fetchObject(__CLASS__)) {
$users[] = $user;
}
return $users;
}
public static function GetUserByName($name) {}
public static function GetUserByID($name) {}
public function checkPassword($password) {return $this->password == $password;}
public function showLink() {return "<a href=\"user.php?i={$this->id}\">{$this->name}</a>";}
}
$user = new User();
$user->name = 'oct1158';
$user->password = '789012';
$user->useFunction('birthday', 'NOW()');
echo 'Field birthday uses MySQL Function: ', $user->birthday, '<br>';
if ($user->insert()) {
echo 'New User ID: ', $user->id, '<br>';
$user->password = '112233';
$user->update();
} else {
echo 'INSERT Failed<br>';
}
$sql = 'SELECT * FROM Users WHERE UserName = ?';
$stmt = $dbh->prepare($sql);
$stmt->execute(array('admin'));
$admin_user = $stmt->fetchObject('User');
echo 'Admin ID is ', $admin_user->id, '.<br>';
echo 'Admin Birthday is ', $admin_user->birthday, '.<br>';
$users = User::GetAll();
echo '<br>';
echo $users[0]->name, ', ', $users[0]->birthday, '<br>';
echo $users[1]->name, ', ', $users[1]->birthday, '<br>';
echo $users[2]->name, ', ', $users[2]->birthday, '<br>';
echo '<br>';
$user = new User();
$user->insert();
$user->delete();
?>
DataObject 类示例
<?php
class DataObject {
private $changedFields = array(); private $data = array(); private $funcFields = array(); function __get($property) {
if (isset($this::$_propertyList[$property])) {
return $this->data[$this::$_propertyList[$property]]; } else {
return $this->$property; }
}
function __set($property, $value) {
if (isset($this::$_propertyList[$property])) {
$field = $this::$_propertyList[$property];
$this->data[$field] = $value; if (!in_array($field, $this->changedFields)) {
array_push($this->changedFields, $field);
}
$index = array_search($field, $this->funcFields);
if ($index !== false) {
unset($this->funcFields[$index]);
$this->funcFields = array_values($this->funcFields);
}
} else {
$this->data[$property] = $value; }
}
private function checkPrimaryKey() {}
private function clear() {}
public function delete() {}
public function insert() {}
public function update() {}
public function useFunction($property, $function) {}
}
?>